Template metaprogramming
- C++ course
- Expert
- Lesson 1/47
- 5 min
Learn compile-time computation with template metaprogramming.
Template metaprogramming
Template metaprogramming (TMP) uses templates to do computations at compile time. A template can take a non-type parameter instead of a type: template <int N> struct Double { static const int value = N * 2; };. Here N is an int value known at compile time.
The result is a constant accessed as Double<5>::value, which equals 10. This value is baked into the executable as a ready number; no computation happens at run time. TMP is used to produce compile-time constants.
Accessing via ::value
To read the result you write the template name, the value in angle brackets and ::value. Example: Double<7>::value yields 14. The compiler computes value = 7 * 2 at compile time for Double<7>.
You can print these constants with std::cout: std::cout << Double<7>::value; prints 14. The optimizer turns this constant directly into a number.
Practice Define the Double template
Define template <int N> struct Double with static const int value = N * 2; inside. In main write std::cout << Double<7>::value;.
Starter code
#include <iostream>
// Define the Double template here
int main() {
// Print the result
return 0;
}Sample solution
#include <iostream>
template <int N>
struct Double {
static const int value = N * 2;
};
int main() {
std::cout << Double<7>::value;
return 0;
}Expected output
14
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does template <int N> struct Double produce?
template <int N> struct Double { static const int value = N * 2; };- A run-time variable
- A compile-time constant Correct answer
- A function
- A macro
Explanation: Double<5>::value is computed as 10 at compile time.
2 Complete the multiplier
template <int N> struct Double { static const int value = N * ____; };
template <int N> struct Double { static const int value = N * 2; };
Explanation: Write value = N * 2; the multiplier for double is 2.
3 Match each piece to its role
| Term | Meaning |
|---|---|
template <int N> |
Non-type parameter |
static const int value |
Compile-time result |
Double<5>::value |
Constant access |
struct Double |
Template struct |