简体   繁体   English

将可变参数类型列表转换为对的元组

[英]Transform variadic type list to tuple of pairs

Is the following type transformation possible:是否可以进行以下类型转换:

T1, T2, T3, T4, ...., T2n-1, T2n 
    ---> transform to --->
tuple<
  pair<T1, T2>, 
  pair<T3, T4>, 
  ..., 
  pair<T2n-1, T2n>
>

Such a meta-function这样的元功能

template <class... Args>
using split_in_pairs_t = ???

would be used like so:会像这样使用:

template <class... Args>
class UseCase
{
  split_in_pairs_t<Args...> _tupleOfPairs;
};

A non-recursive solution would be preferable.非递归解决方案将是可取的。

Make an index sequence of half the size, and pair elements 2*i, 2*i+1 together:制作一个大小为一半的索引序列,并将元素2*i, 2*i+1配对在一起:

template <class...> struct pairwise_impl;

template <class... Args, size_t... Is> 
struct pairwise_impl<std::tuple<Args...>, std::index_sequence<Is...>>
{
    using full_tuple_t = std::tuple<Args...>;
    
    using type = std::tuple<std::pair<
        std::tuple_element_t<2*Is, full_tuple_t>,
        std::tuple_element_t<2*Is+1, full_tuple_t>
    >...>;
};

template <class... Args> struct pairwise
{
    static_assert(sizeof...(Args) % 2 == 0,
                   "Only even typelists can be split to pairs");
    
    using type = typename pairwise_impl<
        std::tuple<Args...>, 
        std::make_index_sequence<sizeof...(Args) / 2>
    >::type;           
};  

template <class... Args>
using pairwise_t = typename pairwise<Args...>::type;

Demo演示

Using Boost.Mp11 , this is a short one-liner (as always):使用Boost.Mp11 ,这是一个简短的单行(一如既往):

template <class... Args>
using split_in_pairs_t =
    mp_pairwise_fold<std::tuple<Args...>, std::pair>;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM