来自整数的可变参数模板参数

Reg*_*lez 10 c++ variadic-templates

鉴于我有那种类型

template<int ...Is>
struct A {};
Run Code Online (Sandbox Code Playgroud)

我可以A<0, 1, 2, 3, 4, 5,..., d>仅从整数d “生成”类型吗?

我想到了类似的东西

template<int d>
struct B : A<std::index_sequence<d>...> {}
Run Code Online (Sandbox Code Playgroud)

但这不起作用。

另一种选择是手动专门化:

template<int d>
struct B;

template<>
struct B<0>: A<> {};

template<>
struct B<1>: A<0> {};

template<>
struct B<2>: A<0, 1> {};

template<>
struct B<3>: A<0, 1, 2> {};
Run Code Online (Sandbox Code Playgroud)

但显然我不能写 B<3000> b;

[实际]我的用例比这更复杂。我不想重新实现std :: integer_sequence,但是要更复杂一些。

Evg*_*Evg 16

标准库中已经有了您想要的- std::make_integer_sequence。如果要使用自己的类型A<...>,可以执行以下操作:

template<int... Is>
struct A {};

template<class>
struct make_A_impl;

template<int... Is>
struct make_A_impl<std::integer_sequence<int, Is...>> {
    using Type = A<Is...>;
};

template<int size>
using make_A = typename make_A_impl<std::make_integer_sequence<int, size>>::Type;
Run Code Online (Sandbox Code Playgroud)

然后A<0, ..., 2999>

make_A<3000>
Run Code Online (Sandbox Code Playgroud)