constexpr evaluation — evaluate functions at compile time.
1// C++11: limited constexpr2constexpr int factorial(int n) {3 return (n <= 1) ? 1 : n * factorial(n - 1);4}56constexpr int f5 = factorial(5); // 120 at compile time78// C++20: constexpr dynamic allocation, virtual, try-catch9constexpr std::vector<int> make_vec() {10 std::vector<int> v;11 for (int i = 0; i < 10; i++) {12 v.push_back(i * i);13 }14 return v;15}1617constexpr auto squares = make_vec();1819// consteval — must run at compile time20consteval int square(int n) {21 return n * n;22}2324int x = square(5); // OK25// int y = square(x); // Error — not compile-time2627// constexpr if28template<typename T>29auto process(T val) {30 if constexpr (std::is_integral_v<T>) {31 return val * 2;32 } else {33 return val + 0.5;34 }35}
Keywords: