多次展开参数包

3

是否可以多次解包参数包?

例如:我想要获得一个包含4个向量的元组 - 2个整数类型和2个浮点类型。 为了创建这样的元组,我想使用以下语法:

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">
}
2个回答

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...> {};

诀窍在于早期创建一个元组,这样我们就可以同时保留多个模板参数包。

1
这可以使用C++14的integer_sequence完成。如果您没有该功能,这里有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;
};
< p > ExampleClass<2, int, float>::typestd::tuple<std::vector<int>, std::vector<float>, std::vector<int>, std::vector<float>>

在线演示


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接