libcruft-util/variadic.hpp

86 lines
2.8 KiB
C++

/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright 2017-2018 Danny Robson <danny@nerdcruft.net>
*/
#ifndef CRUFT_UTIL_VARIADIC_HPP
#define CRUFT_UTIL_VARIADIC_HPP
#include <cstddef>
#include <type_traits>
#include <utility>
#include <tuple>
namespace util::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> && ...))
{ ; }
///////////////////////////////////////////////////////////////////////////
/// Returns the argument at index `IndexV', as if we called:
/// std::get<N> (std::make_tuple (...))
template <std::size_t IndexV, typename HeadT, typename ...TailT>
auto
get (HeadT &&head, TailT &&...tail) noexcept ((std::is_nothrow_move_constructible_v<TailT> && ...))
{
static_assert (IndexV < sizeof... (TailT) + 1, "Index is out of bounds");
if constexpr (IndexV == 0)
return std::forward<HeadT> (head);
else
return get<IndexV-1> (std::forward<TailT> (tail)...);
}
///////////////////////////////////////////////////////////////////////////
/// 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)...);
}
};
#endif