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
I suppose this is exactly what you asked for:
#include
#include
constexpr int N{4};
constexpr std::array shape {{1,3,5,2}};
// Diagnositcs
template
struct TPrintf {
constexpr static void call(V v, Vals ...vals) {
std::cout << v << " ";
TPrintf::call(vals...);
}
};
template
struct TPrintf {
constexpr static void call(V v) {
std::cout << v << std::endl;
}
};
template
constexpr void t_printf(Vals ...vals) {
TPrintf::call(vals...);
}
// Unroll
template
struct NestedLoops {
template
constexpr static void call(const F& f, RtIdx ...idx) {
for(int i = 0; i < shape[CtIdx]; ++i) {
NestedLoops::call(f, idx..., i);
}
}
};
template
struct NestedLoops {
template
constexpr static void call(const F& f, RtIdx ...idx) {
for(int i = 0; i < shape[N-1]; ++i) {
f(idx..., i);
}
}
};
template
void nested_loops(const F& f) {
NestedLoops<0, F>::call(f);
}
int main()
{
auto lf = [](int i, int j, int k, int l) {
t_printf(i,j,k,l);
};
nested_loops(lf);
return 0;
}