Jaskamal Kainth

Template Metaprogramming - Factorial

Another classic example of template metaprogramming is computing factorials at compile time.

Factorial Implementation

template<int N>
struct Factorial {
    static const int value = N * Factorial<N-1>::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:

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.