Summary - Metaprogramming
- C++ course
- Expert
- Lesson 6/47
- 5 min
Combine recursive templates, constexpr and consteval to write a factorial.
Summary - Metaprogramming
In this group you saw three paths to compile-time computation: recursive templates, constexpr functions and consteval. All of them bake constants into the executable; the difference is flexibility versus strictness.
Now you will combine them into a constexpr factorial. This function delivers the recursive template's behavior with a constexpr function; constexpr int factorial(int n) is usable at both compile time and run time.
constexpr factorial
Inside a constexpr function you write the base case if (n <= 1) return 1; and the recursive step return n * factorial(n - 1);. When called with a constant argument the compiler unfolds the chain at compile time.
Example: constexpr int f = factorial(5); produces the constant f = 120. This is the same as the recursive template but without template syntax; the code is readable.
Practice Write the constexpr factorial
Write constexpr int factorial(int n). Body: if (n <= 1) return 1; return n * factorial(n - 1);. In main define constexpr int f = factorial(5); and write std::cout << f;.
Starter code
#include <iostream>
// Define the constexpr factorial function here
int main() {
// define f and print it
return 0;
}Sample solution
#include <iostream>
constexpr int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
int main() {
constexpr int f = factorial(5);
std::cout << f;
return 0;
}Expected output
120
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which tool runs only at compile time?
constexpr int f(int);
consteval int g(int);
template <int N> struct S { static const int value = N; };- template struct
- constexpr
- consteval Correct answer
- inline
Explanation: consteval runs only at compile time.
2 Complete the recursive step
constexpr int factorial(int n) { return n * factorial(n - ____); }
constexpr int factorial(int n) { return n * factorial(n - 1); }
Explanation: n * factorial(n-1) is the recursive step.
3 Match each tool to its trait
| Term | Meaning |
|---|---|
recursive template |
Template specialization |
constexpr |
Flexible compile/run |
consteval |
Compile-time only |
Typelist |
Type pack |