c++ - 没有 constexpr 的前向声明 - 原因是什么?
问题描述
在learncpp.com 的这一章中,我发现constexpr
变量不能被前向声明(因此给它们的标识符提供与extern
关键字的外部链接是没有意义的)。我不明白为什么在没有变通方法的情况下不能全局使用常量变量,比如将它们定义为头文件中的内联变量。
这样做有设计原因或优势吗?
在 'contstants.h' 中使用 constexpr 的示例:
#ifndef CONSTANTS_H
#define CONSTANTS_H
// define your own namespace to hold constants
namespace constants
{
inline constexpr double pi { 3.14159 }; // note: now inline constexpr
inline constexpr double avogadro { 6.0221413e23 };
inline constexpr double my_gravity { 9.2 }; // m/s^2 -- gravity is light on this planet
// ... other related constants
}
#endif
默认情况下,普通全局具有外部链接:
double g_pi { 3.14159 };; // non-constant globals are external by default. So easy!!
解决方案
推荐阅读
- google-cloud-platform - 在 GCS 存储桶内移动大量文件夹和文件
- robolectric - 在 Android Studio 上使用 RobolectricTestRunner 运行 junit 时出现 NullPointerException 错误
- html - GitHub页面无法加载资源并给出404错误,但在本地运行时加载正常
- javascript - 为什么这个测验不显示问题?
- riscv - 构建VCS模拟器后如何使verilog为CAD工具做好准备
- reactjs - 发现现代中继的路由不起作用
- amazon-web-services - CloudFront 源响应返回状态:“403”
- node.js - 无法让 imBack 使用设置为与团队合作的自适应卡片
- powershell - 从 dockerfile 构建 docker 映像时,意外标记 `(' 附近的语法错误
- php - 在 WooCommerce 结帐页面中将用户地理定位的国家/地区设置为默认值