【问题标题】:Unpacking std::pair<T,std::pair<U, std::pair<...>>> to tuple<T,U,...>将 std::pair<T,std::pair<U, std::pair<...>>> 解包为 tuple<T,U,...>
【发布时间】:2013-06-25 01:15:06
【问题描述】:

所以我试图想出一个函数来转换 a;

std::pair<T,std::pair<U, V>>

数据类型,变成std::tuple

std::tuple<T,U,V>

它应该在一般情况下工作,具有任意数量的混合类型参数,对的格式是这样的;

  • “汽车”始终是一种类型,
  • “cdr”将始终是std::pair
    • 除了最里面的情况,“cdr”本身就是一个类型
      (但是这可能是 std::pair 本身,因为类型是任意的)。

我想要检索的参数的数量和类型是通过可变参数模板参数预先知道的。

我目前的进度有点低,我一直在尝试一些事情,但是我需要的代码似乎是这样的;

std::make_tuple(get<0>(pair), get<0>(get<1>(pair), get<0>(get<1>(get<1>(pair), ..., get<1>(pair)))));

但是我似乎无法找到自动生成它的方法,我尝试了 Sequence&lt;int...&gt; 方法,但没有运气,但我确实认为这是我需要考虑的事情,例如获得方法,它采用可变数量的索引,并使用这些索引多次查找,使用普通的 get 方法?

【问题讨论】:

    标签: templates c++11 tuples std-pair stdtuple


    【解决方案1】:

    简单的递归怎么样

    #include <utility>
    #include <tuple>
    
    // 1. metafunction to concatenate a type and a tuple
    template<typename T, typename U> struct tuple_prepend_type;
    
    template<typename T, typename ...U>
    struct tuple_prepend_type<T, std::tuple<U...>>
    {
        using type = std::tuple<T, U...>;
    };
    
    // 2. is_pair type trait
    template<typename>
    struct is_pair : std::false_type {};
    template<typename U, typename V>
    struct is_pair<std::pair<U, V>> : public std::true_type {};
    
    // 3. the converter itself
    template<typename T, typename = void>
    struct pairs_to_tuple {
        using type = std::tuple<typename T::first_type,
                                typename T::second_type>;
    };
    
    template<typename T>
    struct pairs_to_tuple<T, typename std::enable_if<
                             is_pair<typename T::second_type>::value
                         >::type
             >
    {
        using type = typename tuple_prepend_type<
                         typename T::first_type,
                         typename pairs_to_tuple<typename T::second_type>::type
                     >::type;
    };
    
    int main()
    {
        std::pair<int, std::pair<double, std::pair<bool, char> > > p;
        static_assert(std::is_same<pairs_to_tuple<decltype(p)>::type,
                                   std::tuple<int, double, bool, char>>::value, "")
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-07
      • 2023-02-16
      • 2011-12-16
      • 1970-01-01
      相关资源
      最近更新 更多