Template Metaprogramming - I still don't get it :(

n00ki3 picture n00ki3 · Aug 3, 2009 · Viewed 14.4k times · Source

I have a problem... I don't understand template metaprogramming.

The problem is, that I’ve read a lot about it, but it still doesn’t make much sense to me.

Fact nr.1: Template Metaprogramming is faster

template <int N>
struct Factorial 
{
    enum { value = N * Factorial<N - 1>::value };
};
 
template <>
struct Factorial<0> 
{
    enum { value = 1 };
};
 
// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
    int x = Factorial<4>::value; // == 24
    int y = Factorial<0>::value; // == 1
}

So this metaprogram is faster ... because of the constant literal.

BUT: Where in the real world do we have constant literals? Most programs I use react on user input.

FACT nr. 2 : Template metaprogramming can accomplish better maintainability.

Yeah, the factorial example may be maintainable, but when it comes to complex functions, I and most other C++ programmers can't read them.

Also, the debugging options are very poor (or at least I don't know how to debug).

When does template metaprogramming make sense?

Answer

Daniel Earwicker picture Daniel Earwicker · Aug 3, 2009

Just as factorial is not a realistic example of recursion in non-functional languages, neither is it a realistic example of template metaprogramming. It's just the standard example people reach for when they want to show you recursion.

In writing templates for realistic purposes, such as in everyday libraries, often the template has to adapt what it does depending on the type parameters it is instantiated with. This can get quite complex, as the template effectively chooses what code to generate, conditionally. This is what template metaprogramming is; if the template has to loop (via recursion) and choose between alternatives, it is effectively like a small program that executes during compilation to generate the right code.

Here's a really nice tutorial from the boost documentation pages (actually excerpted from a brilliant book, well worth reading).

http://www.boost.org/doc/libs/1_39_0/libs/mpl/doc/tutorial/representing-dimensions.html