Here is a nice example of static recursion - we will calculate factorials at compile time:

template<int NUM>
struct factorial {
   enum { value = NUM * factorial<NUM-1>::value };

struct factorial<1> {
   enum { value = 1 };

void test(void) {
   std::cout << "factorial(5)=" << factorial<5>::value << std::endl;
   std::cout << "factorial(10)=" << factorial<10>::value << std::endl;



You can think of this template class as a function, with "return value" in form of value, and specialized version is added for NUM=1 instead of the if which stops the recursion.

Also note that the value is defined ("returned") inside enum, the other option you could think of would be static const int, but you can get linker error if defining this value inside the class (and including it from different CPP fies).

Last edited Nov 29, 2007 at 6:50 PM by migo, version 1


vmont Feb 27, 2009 at 10:19 PM 
Truly ingenious!! Thanks for the example.