【现代C++】常量求值

现代C++(特别是C++11及以后的版本)增强了对编译时常量求值的支持,包括constexpr函数、constinitconsteval关键字。这些特性允许在编译时进行更多的计算,有助于优化运行时性能并确保编译时的数据不变性。

1. constexpr - 编译时常量表达式

constexpr指示编译器尽可能在编译时求值。

cpp 复制代码
constexpr int factorial(int n) {
    return (n <= 1) ? 1 : (n * factorial(n - 1));
}

constexpr int val = factorial(5); // 编译时计算5的阶乘

void constexprExample() {
    static_assert(val == 120, "Factorial of 5 should be 120");
}

2. consteval - 强制编译时求值

C++20引入的consteval确保函数必须在编译时求值。

cpp 复制代码
consteval int square(int n) {
    return n * n;
}

constexpr int squaredVal = square(5); // 编译时计算5的平方

void constevalExample() {
    static_assert(squaredVal == 25, "Square of 5 should be 25");
    // int runtimeVal = square(6); // 错误:consteval函数必须在编译时求值
}

3. constinit - 确保静态和线程局部变量在编译时初始化

constinit确保变量在编译时初始化,但与constexpr不同,它不要求变量在其生命周期内都是常量。

cpp 复制代码
constinit static int staticVal = factorial(4); // 编译时计算4的阶乘

void constinitExample() {
    static_assert(staticVal == 24, "Factorial of 4 should be 24");
    // staticVal = 5; // 允许在运行时修改值
}

4. 编译时与运行时的区分

通过使用这些特性,开发者可以明确地指示哪些计算应该在编译时进行,哪些在运行时进行,提高代码的可预测性和效率。

cpp 复制代码
constexpr int compileTimeCalculation = factorial(5); // 编译时求值
int runtimeCalculation = factorial(5); // 运行时求值

void compileTimeVsRuntime() {
    static_assert(compileTimeCalculation == 120, "Compile-time and runtime results should match");
    std::cout << "Runtime calculation: " << runtimeCalculation << std::endl;
}
相关推荐
澈2071 分钟前
C++内存管理:new/delete与内存泄漏实战
开发语言·c++·内存分区
星星码️2 分钟前
LeetCode刷题简单篇之反转字母
c++·算法·leetcode
其实防守也摸鱼6 分钟前
VS code怎么使用 Conda 安装预编译包
开发语言·网络·c++·vscode·安全·web安全·conda
默子昂8 分钟前
langchain 基本使用
开发语言·python·langchain
yaoxin52112310 分钟前
402. Java 文件操作基础 - 读取二进制文件
java·开发语言·python
Hello.Reader15 分钟前
ds4.c 深度解析为 DeepSeek V4 Flash 打造的本地推理引擎
c语言·开发语言
naturerun26 分钟前
螺旋形遍历奇数阶矩阵
c++·算法·矩阵
TopGames29 分钟前
〖Unity GPU粒子插件〗ParticleSystem的终极性能优化方案 十倍百倍的显著提升 现有特效转GPU粒子 高性能特效方案
java·开发语言
Chase_______1 小时前
计算机数据存储全解:从底层进制转换到存储介质演进
java·开发语言·python
栉甜1 小时前
Js进阶(4)
开发语言·javascript·原型模式