Skip to content

Metaprogramming

Metaprogramming

Template metaprogramming is a family of techniques to create new types and compute values at compile time. C++ templates are Turing complete if there are no limits to the amount of recursive instantiations and the number of allowed state variables.

Erwin Unruh was the first to demonstrate template metaprogramming at a committee meeting by instructing the compiler to print out prime numbers in error messages. The standard recommends an implementation support at least 1024 levels of recursive instantiation, and infinite recursion in template instantiations is undefined behavior.

1
2
3
4
5
6
7
template <unsigned n> struct factorial {
    enum { value = n * factorial<n - 1>::value };
};

template <> struct factorial<0> {
    enum { value = 1 };
};

1
std::cout << "factorial<7>::value : " << factorial<7>::value << '\n';

1
constexpr int factorial2(int n) { return n <= 1 ? 1 : (n * factorial2(n - 1)); }

1
std::cout << "factorial<7>::value : " << factorial<7>::value << '\n';

1
2
3
4
5
6
7
struct MyClass {
    template <typename... Tail> static int count() { return 0; }

    template <char Head, char... Tail> static int count() {
        return 1 + count<Tail...>();
    }
};

1
2
std::cout << "MyClass::count<'f','o','o'>(): "
          << MyClass::count<'f', 'o', 'o'>() << '\n'; // 3

Share Snippets