--- title: "Template metaprogramming in C++: compile-time factorial" description: "Compute factorials at compile time in C++ with a recursive class template and a Factorial<0> base case, so the result has no runtime cost." date: 2023-04-06 last_modified_at: 2026-10-02 keywords: [C++, template metaprogramming, compile-time computation, factorial, templates] --- # Template Metaprogramming - Factorial Another classic example of template metaprogramming is computing factorials at compile time. ## Factorial Implementation ```cpp template struct Factorial { static const int value = N * Factorial::value; }; // Base case template<> struct Factorial<0> { static const int value = 1; }; ``` This implementation allows factorial computations to be performed during compilation. The template is recursively instantiated until it reaches the base case of `Factorial<0>`, which returns 1. To use this implementation, simply access the `value` member of the appropriate template instantiation: ```cpp int main() { std::cout << "Factorial of 5: " << Factorial<5>::value << std::endl; // 120 return 0; } ``` The computation happens at compile time, resulting in no runtime overhead for the calculation.