Metaprogramming
- C++ course
- Expert
- Lesson 44/47
- 6 min
Generate compile-time code with template metaprogramming.
Factorial with template metaprogramming
With template metaprogramming you can compute factorial at compile time. The general case refers to itself: Factorial<N>::value = N * Factorial<N-1>::value. The base case is given as a specialization: template <> struct Factorial<0> { static const int value = 1; };.
The compiler unfolds 5 * 4 * 3 * 2 * 1 * 1 for Factorial<5> at compile time and bakes 120 into the executable as a constant. No computation happens at run time. We add this template next to the previous lesson's Engine skeleton.
Accessing Factorial<5>::value
To read the result you write the template name, the value in angle brackets and ::value: Factorial<5>::value. The compiler turns this into the constant 120. You can print it with std::cout: std::cout << Factorial<5>::value; prints 120.
To put the output on a new line we add std::endl. So 120 appears under the previous lesson's Ready output. Each lesson keeps the previous output and adds a new line. This cumulative structure shows the project growing step by step.
Practice Add the Factorial template and call it
Take the previous lesson's Engine skeleton. Before the Engine class define template <int N> struct Factorial with body static const int value = N * Factorial<N-1>::value;. Add the base case specialization template <> struct Factorial<0> { static const int value = 1; };. In main after std::cout << "Ready" << std::endl; add std::cout << Factorial<5>::value;.
Starter code
#include <iostream>
class Engine {
public:
static const int Version = 1;
};
// Define the Factorial template here
int main() {
std::cout << "Ready" << std::endl;
// Print the result
return 0;
}Sample solution
#include <iostream>
class Engine {
public:
static const int Version = 1;
};
template <int N>
struct Factorial {
static const int value = N * Factorial<N - 1>::value;
};
template <>
struct Factorial<0> {
static const int value = 1;
};
int main() {
std::cout << "Ready" << std::endl;
std::cout << Factorial<5>::value;
return 0;
}Expected output
Ready 120
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the base case
template <> struct Factorial<0> { static const int value = ____; };
template <> struct Factorial<0> { static const int value = 1; };
Explanation: Write value = 1; factorial of 0 is 1.
2 What is Factorial<5>::value?
Factorial<5>::value- 60
- 720
- 25
- 120 Correct answer
Explanation: 5! = 5 * 4 * 3 * 2 * 1 = 120.
3 Match each piece to its role
| Term | Meaning |
|---|---|
template <int N> |
Non-type parameter |
Factorial<N-1>::value |
Recursive reference |
template <> struct Factorial<0> |
Base case specialization |
Factorial<5>::value |
Constant access |