// constexpr: 可能编译期也可能运行期// consteval: 必须在编译期执行consteval int compileOnly(int n) { return n * n;}constexpr int x = compileOnly(5); // ✅ 编译期int n;// int y = compileOnly(n); // ❌ 编译错误:不能在运行期调用// 使用场景:确保某个计算一定在编译期完成consteval size_t strlen_ct(const char *s) { size_t n = 0; while (*s++) ++n; return n;}
constexpr 容器(C++20)
// vector 和 string 可以在 constexpr 中使用!constexpr int sumFirstN(int n) { vector<int> v; for (int i = 1; i <= n; ++i) v.push_back(i); int total = 0; for (int x : v) total += x; return total;}// ⚠️ constexpr 中 new 的内存必须在编译期内 deleteconstexpr int s100 = sumFirstN(100); // 5050,编译期计算
实战场景
场景 1:编译期字符串哈希
constexpr uint64_t hash(const char *s) { uint64_t h = 14695981039346656037ULL; while (*s) { h ^= static_cast<uint64_t>(*s++); h *= 1099511628211ULL; } return h;}switch (hash(str)) { // 编译期哈希 → switch 直接用于字符串匹配 case hash("start"): /*...*/ break; case hash("stop"): /*...*/ break;}
场景 2:编译期查表
// 编译期生成 sin 值表template <size_t N>constexpr array<double, N> sinTable() { array<double, N> table{}; for (size_t i = 0; i < N; ++i) table[i] = sin(2 * M_PI * i / N); return table;}constexpr auto sinLUT = sinTable<360>(); // 360 个值在编译期算完double fastSin(int deg) { return sinLUT[deg % 360]; }
场景 3:类型安全的单元量纲
template <int M, int K, int S>struct Unit { double value; template <int M2, int K2, int S2> constexpr auto operator*(Unit<M2, K2, S2> other) const { return Unit<M + M2, K + K2, S + S2>{value * other.value}; }};using Meter = Unit<1, 0, 0>;using Second = Unit<0, 0, 1>;using Speed = Unit<1, 0, -1>; // m/sconstexpr Meter m{10};constexpr Second s{2};constexpr Speed v = m / s; // 编译期计算:Unit<1,0,-1> 类型安全