Search code examples
c++variadic-templates

Variadic template parameters from integer


Given I have that type

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

Can I "generate" the type A<0, 1, 2, 3, 4, 5,..., d> just from an integer d?

I thought about something like

template<int d>
struct B : A<std::index_sequence<d>...> {}

but it doesn't work.

Other option is to specialize manually:

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

but obviously I don't be able to write B<3000> b;

[edit] my actual use-case is a "bit" more complex than that. I don't want to reimplement std::integer_sequence, but something more complex.


Solution

  • We already have what you want in the Standard library - std::make_integer_sequence. If you want to use your own type A<...> you can do this:

    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;
    

    And then for A<0, ..., 2999> write

    make_A<3000>