【现代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;
}
相关推荐
长流小哥18 分钟前
Linux网络编程实战:从字节序到UDP协议栈的深度解析与开发指南
linux·c语言·开发语言·网络·udp
幼儿园园霸柒柒25 分钟前
第七章:7.2求方程a*x*x+b*x+c=0的根,用3个函数,分别求当:b*b-4*a*c大于0、等于0和小于0时的根并输出结果。从主函数输入a、b、c的值
c语言·开发语言·算法·c#
不知道叫什么呀31 分钟前
【C语言基础】C++ 中的 `vector` 及其 C 语言实现详解
c语言·开发语言·c++
muyouking111 小时前
0.深入探秘 Rust Web 框架 Axum
开发语言·前端·rust
勇敢牛牛_1 小时前
【Rust基础】使用Rocket构建基于SSE的流式回复
开发语言·后端·rust
汇太浪1 小时前
第十六届蓝桥杯大赛软件赛省赛 C++ 大学 B 组 部分题解
c++·蓝桥杯
斯普信专业组1 小时前
从原理到实践:NFS复杂故障处理方法论
开发语言·nfs
WW_千谷山4_sch1 小时前
MYOJ_11700(UVA10591)Happy Number(快乐数)(超快解法:图论思想解题)
c++·算法
郭涤生1 小时前
QML 信号与槽
c++·笔记·qt
钢铁男儿1 小时前
Python 文本和字节序列(处理文本文件)
开发语言·python