# Template metaprogramming II: Openning the box

**Posted:**April 22, 2010

**Filed under:**C++, Templates Leave a comment

We saw last time how to print a factorial using only template metaprogramming, but didn’t explain anything about it. I promised to fix that in this article. Starting by the very beginning:

template <int N> struct Factorial { static const int result = N * Factorial::result; }; template <int N> struct Factorial<0> { static const int result = 1; }; #include int main() { std::cout << Factorial<5>::result << "n"; retrun 0; }

–

### Why static const?

If this is starting to remind you of anything then you are crazier than you think, and you already know some Haskel. Indeed, template metaprogramming has some resemblance to Haskel programming: no const “variables”, no for-loop (only recursion), base cases (pattern matching), and cryptic error messages which makes you want to jump of a cliff.

A useful trick I learned when working with Haskel (many many years ago) is to declare the problem, instead of thinking it. For our problem the factorial of a number is defined as said number times the factorial of that same number minus one, being the factorial of 0 always 1.

Translating:

// the factorial of a number is defined as said number times // the factorial of that same number minus one template <int N> struct Factorial { static const int result = N * Factorial::result; }; // being the factorial of 0 always 1. template <int N> struct Factorial<0> { static const int result = 1; };

That’s good for a first approach… next time something more complex (and less theory, promise).