capypad
0 day streak
cpp / expert
Snippet

Compile-time Enforcement with consteval

The 'consteval' keyword (C++20) specifies that a function must produce a compile-time constant. Unlike 'constexpr', which allows both compile-time and run-time execution, 'consteval' strictly forbids run-time calls, ensuring zero overhead.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
 
consteval int fast_power(int base, int exp) {
int res = 1;
while (exp > 0) {
res *= base;
--exp;
}
return res;
}
 
int main() {
constexpr int val = fast_power(2, 10); // OK
// int dynamic_val = 5;
// int error = fast_power(dynamic_val, 2); // Error: not a constant expression
std::cout << val << "\n";
}
Breakdown
1
consteval int fast_power
Defines an 'immediate function' that can only be called in contexts that produce constants.
2
constexpr int val = ...
The result is calculated during compilation and embedded as a literal in the binary.