...

/

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 ...

Access this course and 1400+ top-rated courses and projects.