libcruft-util/variadic.hpp

98 lines
3.1 KiB
C++
Raw Normal View History

2015-04-20 17:13:14 +10:00
/*
2018-08-04 15:14:06 +10:00
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
2015-04-20 17:13:14 +10:00
*
* Copyright 2017-2018 Danny Robson <danny@nerdcruft.net>
2015-04-20 17:13:14 +10:00
*/
#ifndef CRUFT_UTIL_VARIADIC_HPP
#define CRUFT_UTIL_VARIADIC_HPP
#include <cstddef>
#include <type_traits>
#include <utility>
2018-03-23 16:40:30 +11:00
#include <tuple>
2015-04-20 17:13:14 +10:00
namespace cruft::variadic {
///////////////////////////////////////////////////////////////////////////
/// do nothing with a set of parameters.
///
/// useful for temporarily silencing unused argument warnings in parameter
/// packs, or for avoiding assignment of [[gnu::warn_unused_result]] to a
/// temporary value we'd just cast to void anyway (GCC#66425).
///
/// it is guaranteed that this function will never be defined out in
/// debug/release/whatever builds. so it is safe to use to guarantee
/// parameter evaluation.
template <typename ...Args>
void
ignore (const Args&...) noexcept ((std::is_nothrow_destructible_v<Args> && ...))
{ ; }
///////////////////////////////////////////////////////////////////////////
namespace detail {
// using the strategy of discarding assignment from:
// https://attugit.github.io/2015/02/Accessing-nth-element-of-parameter-pack/
struct discard {
template <typename ArgsT>
constexpr discard (ArgsT&&...) { ; }
};
template <size_t>
using discard_n = discard;
template <std::size_t N, typename = std::make_index_sequence<N>>
struct getter;
template <std::size_t N, std::size_t... ignore>
struct getter<N, std::index_sequence<ignore...>> {
template <typename ValueT, typename ...TailT>
decltype(auto)
operator() (discard_n<ignore>..., ValueT &&val, TailT&&...) const
{
return std::forward<ValueT> (val);
}
};
}
/// Returns the argument at index `IndexV', as if we called:
/// std::get<N> (std::make_tuple (...))
template <size_t IndexV, typename ...ArgsT>
decltype(auto)
get (ArgsT&& ...args)
{
return detail::getter<IndexV> {}(std::forward<ArgsT> (args)...);
}
2018-03-23 16:40:30 +11:00
///////////////////////////////////////////////////////////////////////////
/// returns a tuple of all arguments that satisfy the trait QueryT
template <template <typename> class QueryT>
auto filter () { return std::tuple {}; }
/// returns a tuple of all arguments that satisfy the trait QueryT
template <
template <typename> class QueryT,
typename HeadT,
typename ...ArgsT
>
auto
filter (HeadT &&head, ArgsT &&...args)
{
if constexpr (QueryT<HeadT>::value)
return std::tuple_cat (
std::tuple (std::forward<HeadT> (head)),
filter<QueryT> (std::forward<ArgsT> (args)...)
);
else
return filter<QueryT> (std::forward<ArgsT> (args)...);
}
};
2015-04-20 17:13:14 +10:00
2015-04-20 17:13:14 +10:00
#endif