c++ - Unroll loop at compile time -
i want write load of lines c++ file of form foo(i)
i = 0,1, ... , n
, there way of doing @ compile time?
i want because i've got templated class:
template <int x> class myclass{ ... }
and want test lots of different values of "x" like:
for (int = 0; < n; i++) { myclass<i> bar; bar.method() }
this doesn't work wants value passed template value determined @ compile time.
i write out whole thing:
myclass<0> bar0; bar0.method(); myclass<1> bar1; bar1.method();
and make define speed bit, like:
#define mymacro(x) myclass<x> bar_x; bar_x.method();
but i'd still have write mymacro
everywhere , i'm going want change range sensible. if write sort of macro version of loop it'd save me lot of time.
update: needed pass variables method made slight changes accepted answer given @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); }
a solution closer "macro way" can template recursivity :
template<int x> class myclass { public: void foo() { std::cout << x << std::endl; } }; template<int x> inline void mytest() { mytest<x - 1>(); myclass<x-1> bar; bar.foo(); } template<> inline void mytest<1>() { myclass<0> bar; bar.foo(); } int main() { mytest<5>(); return 0; }
and output of example :
0 1 2 3 4
Comments
Post a Comment