Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unroll loop at compile time

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); }
like image 239
R.Mckemey Avatar asked Feb 16 '26 06:02

R.Mckemey


1 Answers

A solution closer to the "macro way" can be the 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 the output of this example is :

0
1
2
3
4
like image 84
Pascal Avatar answered Feb 17 '26 19:02

Pascal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!