I want to write a load of lines into a C++ file of the form foo(i)
for i = 0,1, ... , n
, is there a way of doing this at compile time?
I want to do this because I've got a templated class:
template <int X> class MyClass{ ... }
and I want to test it for lots of different values of "X" with something like:
for (int i = 0; i < n; i++) {
MyClass<i> bar;
bar.method()
}
This doesn't work as it wants the value passed as the template value to be determined at compile time.
I could write out the whole thing:
MyClass<0> bar0; bar0.method();
MyClass<1> bar1; bar1.method();
and I could make a define to speed it up a bit, something like:
#define myMacro(x) MyClass<x> bar_x; bar_x.method();
but I'd still have to write myMacro
everywhere and I'm going to want to change the range too often for this to be sensible. If I could write some sort of macro version of a for loop it'd save me a lot of time.
Update: I actually needed to pass variables to my method so I made slight changes to the accepted answer given by @Pascal
template<int X> class MyClass { public: void foo(int Y) { std::cout << X Y<< std::endl; } };
template<int X> inline void MyTest(int Y) { MyTest<X - 1>(Y); MyClass<X-1> bar; bar.foo(Y); }
template<> inline void MyTest<1>(int Y) { MyClass<0> bar; bar.foo(Y); }