cpp / expert
Snippet
Compile-Time Constants with consteval Functions
The consteval keyword (C++20) specifies that a function must produce a compile-time constant. Unlike constexpr, which can be evaluated at runtime, consteval (immediate functions) guarantees that the logic is executed during compilation, or it will fail to compile.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>consteval int fast_power(int base, int exp) {int res = 1;for(int i = 0; i < exp; ++i) res *= base;return res;}int main() {constexpr int val = fast_power(2, 10); // Guaranteed compile-time// int runtime_val = 5;// int err = fast_power(runtime_val, 2); // Error: not a constant expressionstd::cout << val;}
Breakdown
1
consteval int fast_power(int base, int exp)
Defines an immediate function that can only be called with constant expressions.
2
constexpr int val = fast_power(2, 10);
The result is baked into the binary, resulting in zero runtime overhead.