问题
I am trying to fold a parameter pack of N
different types into a std::tuple
of N-1
std::pairs
with respective types.
So for example the expression
ResolveToTupleOfPairs<void, int, long>::Type tuple;
should evaluate to
std::tuple<std::pair<void, int>, std::pair<int, long>> tuple;
So I am searching for an implementation of the ResolveToTupleOfPairs
type to fold the parameter pack as explained. My current implementation follows, but obviously it causes the type to be a tuple of pairs which each hold the same type twice instead of <T0, T1>, <T1, T2>, ...
.
template<typename... T>
struct ResolveToTupleOfPairs {
static_assert(sizeof...(Args) > 1, "need at least two arguments");
using Type = std::tuple<std::pair<T, T>...>;
};
I'm fine with c++17
solutions.
回答1:
We take advantage of the fact that parameter pack expansion is really really smart
template<typename...>
struct fold;
template<size_t... Is, typename... Ts>
struct fold<std::index_sequence<Is...>, Ts...>
{
using tuple = std::tuple<Ts...>;
using type = std::tuple<std::pair<std::tuple_element_t<Is, tuple>,
std::tuple_element_t<Is + 1, tuple>>...>;
};
template<typename... Ts>
using fold_t = typename fold<std::make_index_sequence<sizeof...(Ts) - 1>, Ts...>::type;
Live
来源:https://stackoverflow.com/questions/48965685/folding-a-parameter-pack-of-n-types-into-n-1-pairs