【现代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;
}
相关推荐
郝学胜-神的一滴6 分钟前
跨平台动态库与头文件:从原理到命名的深度解析
linux·c++·程序人生·unix·cmake
代码中介商6 分钟前
C++ 仿函数(Functor)深度解析:从基础到应用
开发语言·c++
王老师青少年编程16 分钟前
csp信奥赛C++高频考点专项训练之字符串 --【字符串基础】:[NOIP 2018 普及组] 标题统计
c++·字符串·csp·高频考点·信奥赛·专项训练·标题统计
小杍随笔21 分钟前
Rust桌面GUI框架:性能优化与实战避坑指南
开发语言·性能优化·rust
二哈赛车手24 分钟前
新人笔记---项目中简易版的RAG检索后评测指标(@Recall ,Mrr..)实现
java·开发语言·笔记·spring·ai
格林威26 分钟前
3D相机视觉检测:环境光太强,结构光点云全是噪点怎么办?
开发语言·人工智能·数码相机·计算机视觉·3d·视觉检测·工业相机
Rust语言中文社区33 分钟前
【Rust日报】2026-05-02 Temper - 用 Rust 编写的 Minecraft 服务器项目发布 0.1.0 版
运维·服务器·开发语言·后端·rust
冯诺依曼的锦鲤38 分钟前
从零实现高并发内存池:TCMalloc 核心架构拆解
c++·学习·算法·架构
爱滑雪的码农1 小时前
Java基础十一 流(Stream)、文件(File)和IO
java·开发语言·python
叶小鸡1 小时前
Java 篇-项目实战-天机学堂(从0到1)-day11
java·开发语言