我有一个简单的类型列表实现;
template<typename... Ts>
struct Typelist
{
static constexpr size_t count{sizeof...(Ts)};
};
我想要做的是为类型列表中的每个类型生成std::tuple
std::vector>
;例如:
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>...>;
};
然而,它一直在随意吐出它预期的类型。我试过在decltype
中包裹Ts,就像这样:
using type = std::tuple<std::vector<decltype(Ts)>...>;
但那也是错误的,而且我猜测我也错误地使用decltype
。
那么,我怎样才能根据我抛出的类型列表创建一个类型向量元组?
答案 0 :(得分:6)
诀窍是使用专业化深入到模板参数。
在-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;
}
答案 1 :(得分:4)
这是达到你想要的另一种方式。它依赖于功能的力量:
#include <cstddef>
#include <tuple>
#include <vector>
#include <utility>
template<typename... Ts>
struct Typelist
{
static constexpr size_t count{sizeof...(Ts)};
};
template<class... ARGS>
std::tuple<std::vector<ARGS>... > typelist_helper(Typelist<ARGS...>);
template<class T>
using vectorOfTuples = decltype(typelist_helper(std::declval<T>()));
struct A{};
struct B{};
struct C{};
using testlist = Typelist<A, B, C>;
vectorOfTuples<testlist> vec;