I have an integer N which I know at compile time. I also have an std::array holding integers describing the shape of an N-dime
Another variant of the same thing:
template
struct Looper
{
template
void operator()(const std::array& shape, Functor functor)
{
for (int index = 0; index < shape[shape_index]; ++index)
{
Looper()
(
shape,
[index, &functor](auto... tail){ functor(index, tail...); }
);
}
}
};
template
struct Looper
{
template
void operator()(const std::array&, Functor functor)
{
functor();
}
};
template
void loop(const std::array& shape, Functor functor)
{
Looper<0, shape_size>()(shape, functor);
}
Example of use:
constexpr size_t N {4};
constexpr std::array shape {{1,3,5,2}};
void f(int i, int j, int k, int l)
{
std::cout
<< std::setw(5) << i
<< std::setw(5) << j
<< std::setw(5) << k
<< std::setw(5) << l
<< std::endl;
}
// ...
loop(shape, f);
Live demo