Templated recursion

To understand what is recursion, you first need to understand what is recursion.

Just discovered the following valid piece of code.
Originally it was printing powers of tree, but it was easy to modify this code so now it supports various bases.

Beautiful, isn’t it?


#include <iostream>
using namespace std;

template<int BASE, int POWER>
class Pow {
public:
 enum { result=BASE * Pow<BASE, POWER-1>::result };
}; 

template<int BASE>
class Pow<BASE, 0> {
public:
 enum { result = 1 };
};

int main(int argc, char * argv[]){

 std::cout << Pow<3, 3>::result << std::endl;
 return 0;
};

The great thing is that both VC 7.1 and gcc 3.2.3 support template recursion.

Leave a Reply