Template Metaprogramming Basics
Prerequisites: Variadic templates
Templates form their own tiny language, evaluated by the compiler
at compile time rather than at runtime — historically used for
compile-time computation before constexpr (next lesson) made much
of it unnecessary:
template<int N>
struct Factorial {
static const int value = N * Factorial<N - 1>::value;
};
template<>
struct Factorial<0> {
static const int value = 1; // base case
};
std::cout << Factorial<5>::value << std::endl; // 120 — computed at compile time
<> after the second Factorial is a template specialization —
an explicit alternate implementation for one specific type or
value, used here as the recursion's base case.
Common mistakes
- Reaching for template metaprogramming where a plain
constexprfunction (next lesson) would be far more readable — modern C++ only needs the technique above for genuinely type-level computation.