Folding a parameter pack of N types into N-1 pairs

醉酒当歌 提交于 2019-12-22 10:52:22

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!