Compile-Time Evaluation (constexpr & C++20 consteval)
🔴 Advanced
📖 Definition
constexpr functions can be evaluated at compile time if arguments are constant expressions. C++20 consteval defines an immediate function that MUST evaluate at compile time, causing a compilation error if called with runtime arguments.
💡 Code Example
#include <iostream>
consteval int factorial(int n) { // C++20 immediate function
return (n <= 1) ? 1 : n * factorial(n - 1);
}
int main() {
constexpr int val = factorial(5); // Computed at compile time (120)
std::cout << "Factorial 5: " << val << "\n";
return 0;
}