Sunday, August 05, 2007

The 'T' Factor

Where 'T' stands for Templates :). I came across this nifty piece of code on the internet.


template<int N>
class Factorial {
public:
enum { value = N * Factorial<N-1>::value };
};

class Factorial<1> {
public:
enum { value = 1 };
};

Yes, it's supposed to compute the factorial of a number with this statement :-

Factorial<N>::value

And all that happens, as with templates, at compile time!.Read this for further explanation.
Wow, so no worrying about integer overflows while computing factorial anymore. As the program won't compile in that case. The possibilities are endless. :)