【现代C++】常量求值

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

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;
}
相关推荐
傲世仙尊8 分钟前
C++起步-命名空间解决命名冲突与cin-cout缺省参数
开发语言·c++
hljqwb12 分钟前
java服务异常日志只打印异常类型,没有堆栈定位分析(十)
java·开发语言
ym hyd 11116 分钟前
生鲜超市库存管理信息系统源码 Java+SpringBoot+Vue3 前后分离
java·开发语言·vue.js·spring boot·毕设
haerapi18 分钟前
KingbaseES 全文检索实战之前:先建立中文搜索的可解释基线
开发语言·python·全文检索
徐小黑ACG18 分钟前
Golang 基础02 控制语句
开发语言·后端·golang
liyunlong-java23 分钟前
敏感词过滤完整指南(DFA 字典树)
java·开发语言·spring
(Charon)25 分钟前
【C++面试】四种cast转换:static_cast、dynamic_cast、const_cast与reinterpret_cast
开发语言·c++·面试
脉动数据行情129 分钟前
Python asyncio 异步实现比特币 BTC 实时行情监听 高并发版
开发语言·python·区块链
爱吃奥利奥_wen29 分钟前
排序算法通关手册:从 O(n²) 到 O(n log n),用一篇文章打通算法内功心法
开发语言·经验分享
外收内放34 分钟前
Python基础语法练习题(55-56)
开发语言·python