Suppose I want to call some templates over and over in a loop, with the loop indexes in the template arguments. Like this (except not illegal):
template <typename T, int k>
T function(T x) {
for (int i = 1; i <= k; ++i) {
for (int j = i - 1; j >= 0; --j) {
constexpr bool method_one_ok = function_of(i, j);
if (method_one_ok) {
x = method_one<T, i, j, k>(x);
} else {
x = method_two<T, i, j, k>(x);
}
}
}
return x;
}
I know how to hobble through it with recursive templates and specializations, but that's a horror I figured out around about C++11 or earlier.
Is there a cleaner way to do this?
Here's a handy function:
It will call a function with every integer in an
integer_sequencewrapped in anintegral_constant. For example:Then with some clever transformations from
0 -> Xto your desired ranges1 -> k+1andi-1 -> -1, you can write:This can be made to work in C++14 by replacing the fold expression:
And can be made C++11 by implementing
std::integer_sequence/std::make_integer_sequencefor C++11.You can make this easier for your specific case by having a helper
range<start, stop>that is an integer sequence from start to stop directly so you don't have to manipulate the function argument.In general, "template loops" are implemented by creating a new pack with
std::index_sequenceand applying it to a function, and folding over that pack.The C++20 solution is to do this totally in line with a lambda with a template parameter list: