2016-06-01 53 views
4

我有一个简单的类型列表实现;从类型列表创建向量的元组

template<typename... Ts> 
struct Typelist 
{ 
    static constexpr size_t count{sizeof...(Ts)}; 
}; 

我想用它来做,是产生std::vector>在类型串每一种类型的std::tuple;例如:

struct A {}; 
struct B {}; 
struct C {}; 

using myStructs = typelist<A,B,C>; 
using myList = tupleOfVectorTypes<myStructs>; tuple<vector<A>, vector<B>, vector<C>> 

这就是我一直在玩弄:

template<template<typename... Ts> class T> 
struct List 
{ 
    using type = std::tuple<std::vector<Ts>...>; 
}; 

然而,一直吐回,它需要一个类型。我已经试过包装TS在decltype,像这样:

using type = std::tuple<std::vector<decltype(Ts)>...>;

但是,这是错误的,以及,我猜我使用decltype不当为好。 那么,我怎么能创建一个类型向量的元组,基于我扔掉的类型列表呢?

回答

5

诀窍是使用专业化深入到模板参数。

-std=c++1z模式下测试用gcc 5.3.1:

#include <vector> 
#include <tuple> 

template<typename... Ts> 
struct Typelist{ 
}; 

// Declare List 
template<class> class List; 

// Specialize it, in order to drill down into the template parameters. 
template<template<typename...Args> class t, typename ...Ts> 
struct List<t<Ts...>> { 
    using type = std::tuple<std::vector<Ts>...>; 
}; 

// Sample Typelist 

struct A{}; 
struct B{}; 
struct C{}; 

using myStructs = Typelist<A,B,C>; 

// And, the tuple of vectors: 

List<myStructs>::type my_tuple; 

// Proof 

int main() 
{ 
    std::vector<A> &a_ref=std::get<0>(my_tuple); 
    std::vector<B> &b_ref=std::get<1>(my_tuple); 
    std::vector<C> &c_ref=std::get<2>(my_tuple); 
    return 0; 
} 
+0

太棒了!我仍然在学习一些关于可变模板的知识,你能解释一下为什么这个模型完全适用吗? 当我看到 'template