I have a code like
template <size_t N>
class A
{
template <size_t N>
someFunctions() {};
};
Now I want to create instances of the class and call the functions in it in a for loop for a set of many values like
// in main()
int main()
{
for (int i = 1; i <= 100; i++)
{
const int N = i; // dont know how to do this
A<N> a;
a.functionCalls();
}
}
How to do this? Hoping for a method to do this.
Just fo completeness - is it really required for the class or function be templated, if the only usage of function is to be called from loop?
If so and you don't want to write by hand take look at boost.hana.
The
N
needs to be compile-time constant, which is with a normalfor
loop is not possible.But, there are many workarounds. For instance, inspired by this SO post, you can do something like the following. (See a Live demo)
Prints
1
to100
In c++17, the above can be reduced to a single template
AGenerator
class(i.e. specialization can be avoided), usingif constexpr
. (See a Live demo)Output:
In case of providing the range of iteration, you could use the following.(See a Live demo)
Outputs the same as the above version.
From C++20, you can use template lambdas, so you can try something as follows
The following is a full compiling example that print all numbers from 0 to 99
One way you can do this is with template meta-programming with something like this:
This would require something called a
template for
which is the expected form expansion statements will take, which is something that look like a for loop but in reality is a templated block in a function that is instanciated multiple times.Of course, there is a workaround. We can abuse generic lambdas to declare some sort of local templated block and instanciate it ourself:
This function takes an integer sequence and instantiate the lambda
F
as many time as the length of the sequence.It is used like this:
Here,
N
can be sent as template parameter because it's an object that has a constexpr conversion operator to an integer type. More precisely, it's astd::integral_constant
with an increasing value.Live example