C++ Compile-Time Programming | `constexpr`, `consteval`, and TMP
이 글의 핵심
A practical tour of compile-time evaluation: from `constexpr` fundamentals to TMP patterns and when to move work back to runtime.
constexpr basics
constexpr int square(int x) {
return x * x;
}
int main() {
constexpr int result = square(5);
int arr[result];
int x = 10;
int result2 = square(x); // may run at runtime
}
constexpr variables & classes
Illustrative Point with constexpr constructor and methods—same as original.
if constexpr (C++17)
See dedicated article: if constexpr.
consteval (C++20)
See consteval.
Examples
Compile-time string hashing, Fibonacci arrays, type checks, sorting constexpr arrays—code mirrors the Korean post.
Template metaprogramming
Factorial struct recursion and simple type lists demonstrate classic TMP; prefer constexpr algorithms when possible for readability.
Performance comparison
Illustrates runtime vs compile-time Fibonacci to motivate where work happens—not a substitute for Big-O analysis of algorithms.
Pitfalls
constexpr restrictions (e.g. no static locals in older rules—check your standard version), runtime inputs, and exponential compile-time recursion.
constexpr vs consteval vs const
const is not necessarily compile-time; constexpr/consteval express stronger guarantees.
FAQ
Topics: when to use constexpr, relation to inline, compile-time cost, C++20 improvements, TMP vs constexpr readability.
Related posts
constexprfunctionsif constexpr- Constexpr basics series
Keywords
C++, constexpr, compile-time, TMP, metaprogramming.
See also
- Compile-time optimization series