...

/

Template Metaprogramming

Template Metaprogramming

In this lesson, we'll learn about template metaprogramming.

Template Metaprogramming

How this all started:

  • 1994 Erwin Unruh discovered template metaprogramming by accident.
  • His program failed to compile but calculated the first 30 prime numbers at compile-time.
  • To prove his point, he used the error messages to display the first 30 prime numbers.

Let’s have a look at the screenshot of the error:

widget

We have highlighted the important parts in red. We hope you can see the pattern. The program calculates at compile-time the first 30 prime numbers. This means template instantiation can be used to do math at compile-time. It gets even better. Template metaprogramming is Turing-complete and can, therefore, be used to solve any computational problem. Of course, Turing-completeness holds only in theory for template metaprogramming because the recursion depth (at least 1024 with C++11) and the length of the names which are generated during template instantiation provide some limitations.

Calculating at Compile-Time

The Factorial program is the Hello World of template metaprogramming.

Press + to interact
template <int N>
struct Factorial{
static int const value= N * Factorial<N-1>::value;
};
template <> struct Factorial<1>{
static int const value = 1;
};
std::cout << Factorial<5>::value << std::endl;
std::cout << 120 << std::endl;

The call Factorial<5>::value ...