Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 807
Regis Portalez Avatar asked May 24 '19 07:05

Regis Portalez


People also ask

How to use variadic function in c++?

Variadic function templates in C++ Variadic templates are class or function templates, that can take any variable(zero or more) number of arguments. In C++, templates can have a fixed number of parameters only that have to be specified at the time of declaration. However, variadic templates help to overcome this issue.

What is Variadic template C++?

A variadic template is a class or function template that supports an arbitrary number of arguments. This mechanism is especially useful to C++ library developers: You can apply it to both class templates and function templates, and thereby provide a wide range of type-safe and non-trivial functionality and flexibility.

What is parameter pack in c++?

Parameter packs (C++11) A parameter pack can be a type of parameter for templates. Unlike previous parameters, which can only bind to a single argument, a parameter pack can pack multiple parameters into a single parameter by placing an ellipsis to the left of the parameter name.


1 Answers

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>
like image 142
Evg Avatar answered Sep 28 '22 06:09

Evg