跳转到内容
主菜单
主菜单
移至侧栏
隐藏
导航
首页
最近更改
随机页面
MediaWiki帮助
代码酷
搜索
搜索
中文(中国大陆)
外观
创建账号
登录
个人工具
创建账号
登录
未登录编辑者的页面
了解详情
贡献
讨论
编辑“︁
C++11 constexpr
”︁(章节)
页面
讨论
大陆简体
阅读
编辑
编辑源代码
查看历史
工具
工具
移至侧栏
隐藏
操作
阅读
编辑
编辑源代码
查看历史
常规
链入页面
相关更改
特殊页面
页面信息
外观
移至侧栏
隐藏
您的更改会在有权核准的用户核准后向读者展示。
警告:
您没有登录。如果您进行任何编辑,您的IP地址会公开展示。如果您
登录
或
创建账号
,您的编辑会以您的用户名署名,此外还有其他益处。
反垃圾检查。
不要
加入这个!
= C++11 constexpr = '''constexpr'''是C++11引入的关键字,用于声明'''编译时常量表达式'''(compile-time constant expression)。它允许在编译期计算表达式的值,从而优化性能并增强类型安全性。 == 核心概念 == === 基本定义 === constexpr可修饰: * 变量:声明该变量必须是编译期常量 * 函数:声明该函数在给定编译期常量参数时可产生编译期常量结果 === 与const的区别 === {| class="wikitable" |+ const vs constexpr ! 特性 !! const !! constexpr |- | 初始化时机 || 运行期或编译期 || '''必须'''在编译期确定 |- | 修饰函数 || 不能保证编译期求值 || 可编译期求值 |- | 数组大小 || C++98中不可用 || 可用作数组维度 |} == 语法规范 == === 变量声明 === <syntaxhighlight lang="cpp"> constexpr int max_size = 100; // 正确:字面量初始化 constexpr double pi = 3.14159; // 正确:浮点字面量 </syntaxhighlight> === 函数声明 === <syntaxhighlight lang="cpp"> constexpr int factorial(int n) { return n <= 1 ? 1 : n * factorial(n - 1); } </syntaxhighlight> == 代码示例 == === 基础示例 === 计算编译期阶乘: <syntaxhighlight lang="cpp"> #include <iostream> constexpr int compute_factorial(int n) { return (n <= 1) ? 1 : (n * compute_factorial(n - 1)); } int main() { constexpr int val = compute_factorial(5); // 编译期计算 int dynamic_val = compute_factorial(5); // 运行期计算 std::cout << "Compile-time: " << val << "\nRuntime: " << dynamic_val; } </syntaxhighlight> {{Output| Compile-time: 120 Runtime: 120 }} === 进阶应用 === 编译期字符串哈希: <syntaxhighlight lang="cpp"> constexpr unsigned int hash_str(const char* s, int off = 0) { return !s[off] ? 5381 : (hash_str(s, off+1) * 33) ^ s[off]; } int main() { constexpr auto hash = hash_str("hello"); static_assert(hash == 2107146360, "Hash mismatch"); } </syntaxhighlight> == 限制条件 == constexpr函数在C++11中需满足: * 函数体必须只有单个return语句(递归除外) * 不能包含: * 循环语句 * goto语句 * 非字面类型的变量 * 未初始化的变量 == 实际应用案例 == === 案例1:固定尺寸数组 === <syntaxhighlight lang="cpp"> constexpr int get_array_size() { return 32; } int main() { int arr[get_array_size()]; // 合法数组声明 } </syntaxhighlight> === 案例2:模板元编程 === 结合模板实现编译期计算: <syntaxhighlight lang="cpp"> template<int N> struct Factorial { static constexpr int value = N * Factorial<N-1>::value; }; template<> struct Factorial<0> { static constexpr int value = 1; }; int main() { static_assert(Factorial<5>::value == 120, ""); } </syntaxhighlight> == 版本演进 == {| class="wikitable" |+ constexpr标准演进 ! 标准 !! 改进 |- | C++11 || 基础功能 |- | C++14 || 放宽函数限制(允许多语句、局部变量等) |- | C++17 || 支持if constexpr |- | C++20 || 支持虚函数、try-catch等 |} == 性能分析 == <mermaid> pie title constexpr优化效果 "编译期计算" : 75 "运行期计算" : 25 </mermaid> 数学公式示例(欧拉公式验证): <math>e^{i\pi} + 1 = 0</math>在编译期验证: <syntaxhighlight lang="cpp"> #include <complex> #include <iostream> constexpr bool verify_euler() { using namespace std::complex_literals; constexpr std::complex<double> res = std::exp(1.0i * 3.1415926535); return (std::abs(res.real() + 1) < 1e-9) && (std::abs(res.imag()) < 1e-9); } static_assert(verify_euler(), "Euler's formula failed"); </syntaxhighlight> == 最佳实践 == * 优先用constexpr替代宏常量 * 对数学计算、查找表等使用constexpr * 注意C++11的限制条件 * 利用static_assert进行编译期验证 {{Warning|过度使用constexpr可能导致编译时间显著增加}} == 参见 == * [[C++14 constexpr]] * [[模板元编程]] * [[编译时计算]] [[Category:编程语言]] [[Category:C++]] [[Category:C++11 新特性]]
摘要:
请注意,所有对代码酷的贡献均被视为依照知识共享署名-非商业性使用-相同方式共享发表(详情请见
代码酷:著作权
)。如果您不希望您的文字作品被随意编辑和分发传播,请不要在此提交。
您同时也向我们承诺,您提交的内容为您自己所创作,或是复制自公共领域或类似自由来源。
未经许可,请勿提交受著作权保护的作品!
取消
编辑帮助
(在新窗口中打开)