如何在命名空间中定义双精度常量?例如:
// constant.h
namespace constant {
static const double PI = 3.1415926535;
}
// No need in constant.cpp
这是最好的方式吗?
如何在命名空间中定义双精度常量?例如:
// constant.h
namespace constant {
static const double PI = 3.1415926535;
}
// No need in constant.cpp
这是最好的方式吗?
I'd say:
-- In c++14:
namespace constant
{
template <typename T = double>
constexpr T PI = T(3.1415926535897932385);
}
-- 在C++11中:
namespace constant
{
constexpr double PI = 3.1415926535897932385;
}
-- 在 c++03 中:
namespace constant
{
static const double PI = 3.1415926535897932385;
}
PI
的类型,如果使用除double以外的其他类型进行操作,则不需要强制转换,而且我没有看到任何开销,除了多一行小代码。 PI
是介绍变量模板的论文中使用的典型示例,对于它解决的更多问题,最好的来源仍然是该论文:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3651.pdf - Draxstatic const double PI;
甚至不应该编译。通常的解决方案是在头文件中只需编写double const PI = 3.14;
。(如果对象是const,则它隐式为static.) - James Kanzedouble const PI = 3.;
没有实际优势,除了增加冗余性。 - James Kanze