是否可以多次打开参数包的包装?
例如:我想得到一个包含4个向量的元组 - 其中2个为int类型,2个为float类型。 要创建这样的元组,我想使用如下语法:
ExampleClass<2, int, float> class;
是否可以创建这样的课程?我正在考虑这样的事情:
template <int numUnpacks, typename ... Types>
class ExampleClass
{
using Types = std::tuple<std::vector<Types>...>; // here i don't know how to unpack "std::vector<Types>...>" as often as "numUnpacks">
}
答案 0 :(得分:1)
通常的递归模板部分特化废话似乎很简单:
template<int n,class T,class... TT>
struct Impl;
template<int n,class... TT,class... UU>
struct Impl<n,std::tuple<TT...>,UU...> :
Impl<n-1,std::tuple<TT...,UU...>,UU...> {};
template<class... TT,class... UU> // just "class T" would be ambiguous
struct Impl<0,std::tuple<TT...>,UU...>
{using Types=std::tuple<std::vector<TT>...>;};
template<int n,class... TT>
struct ExampleClass : Impl<n,std::tuple<>,TT...> {};
诀窍是尽早创建tuple
,以便我们一次可以保留多个模板参数包。
答案 1 :(得分:1)
这可以使用C ++ 14&#39; integer_sequence
来完成。如果您还没有,请implementation Jonathan Wakely。
template <int numUnpacks, typename... Types>
struct ExampleClass
{
template<typename T, size_t>
using T_alias = T;
template<typename T, size_t N, typename I = std::make_index_sequence<N>>
struct repeat;
template<typename T, size_t N, size_t... I>
struct repeat<T, N, std::index_sequence<I...>> {
using type = decltype(std::tuple_cat(std::declval<T_alias<T, I>>()...));
};
using type = typename repeat<std::tuple<std::vector<Types>...>, numUnpacks>::type;
};
ExampleClass<2, int, float>::type
是std::tuple<std::vector<int>, std::vector<float>, std::vector<int>, std::vector<float>>