【现代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;
}
相关推荐
charlie11451419111 分钟前
如何使用Qt创建一个浮在MainWindow上的滑动小Panel
开发语言·c++·qt·界面设计
神仙别闹19 分钟前
基于Python实现LSTM对股票走势的预测
开发语言·python·lstm
chao_7891 小时前
回溯题解——子集【LeetCode】二进制枚举法
开发语言·数据结构·python·算法·leetcode
cpp_learners3 小时前
QML与C++交互之创建自定义对象
c++·qt·qml
尘世闲鱼3 小时前
解数独(C++版本)
开发语言·c++·算法·解数独
kyle~4 小时前
C/C++字面量
java·c语言·c++
纨妙4 小时前
python打卡day59
开发语言·python
wuxuanok4 小时前
Web后端开发-请求响应
java·开发语言·笔记·学习
Sally璐璐4 小时前
IPSAN 共享存储详解:架构、优化与落地实践指南
开发语言·php
Mr.Winter`4 小时前
轨迹优化 | 基于激光雷达的欧氏距离场ESDF地图构建(附ROS C++仿真)
c++·人工智能·机器人·自动驾驶·ros·ros2·具身智能