首页 > 解决方案 > 没有 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!!

标签: c++global-variables

解决方案


推荐阅读