2016-06-01 43 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