CLOSE
Updated on 17 Jun, 20255 mins read 3 views

What is Template Metaprogramming?

Template Metaprogramming is the technique of using the C++ template system to perform computations during compile time. While templates are typically introduced for generic programming, TMP pushes them into a new domain: code that writes code.

Think of it as using the compiler as an interpreter—where logic, decisions, and even data structures can be processed before your program ever runs.

Why Use TMP?

  • Performance: Do computations at compile time to reduce runtime cost
  • Type Safety: Enforce type rules and constraints before runtime
  • Optimization: Enable powerful zero-cost abstractions (e.g., STL, Eigen library)

It’s used heavily in libraries like Boost, the STL, and modern C++ frameworks such as std::variant, std::optional, and std::tuple.

Getting Started: Compile-Time Recursion

Let’s start with a simple example: calculating factorials.

🧾 Compile-Time Factorial

template<int N>
struct Factorial {
    static const int value = N * Factorial<N - 1>::value;
};

template<>
struct Factorial<0> {
    static const int value = 1;
};

Using it:

int main() {
    int result = Factorial<5>::value; // 120
}

What happens here?

  • Factorial<5>::value is resolved at compile time to 120.
  • The compiler unrolls the recursion:

    Factorial<5> → 5 * Factorial<4>
    Factorial<4> → 4 * Factorial<3>
    ...
    Factorial<0> → 1
    

No runtime recursion, no function call stack — just compile-time constant folding.