use*_*020 1 c++ namespaces constants
在命名空间中定义双常量的最佳方法是什么?例如
// constant.h
namespace constant {
static const double PI = 3.1415926535;
}
// No need in constant.cpp
Run Code Online (Sandbox Code Playgroud)
这是最好的方法吗?
我会说:
- 在c ++ 14中:
namespace constant
{
template <typename T = double>
constexpr T PI = T(3.1415926535897932385);
}
Run Code Online (Sandbox Code Playgroud)
- 在c ++ 11中:
namespace constant
{
constexpr double PI = 3.1415926535897932385;
}
Run Code Online (Sandbox Code Playgroud)
- 在c ++ 03中:
namespace constant
{
static const double PI = 3.1415926535897932385;
}
Run Code Online (Sandbox Code Playgroud)
请注意,如果您的常量不具有普通类型并且您在共享库中,我建议避免在全局/命名空间范围内给它内部链接,我不知道关于此的理论,但在实践中它确实倾向于随机乱搞:)