What is the best way to define a double constant in a namespace?

半腔热情 提交于 2020-01-25 04:40:14

问题


What is the best way to define a double constant in a namespace? For example

// constant.h
namespace constant {
    static const double PI = 3.1415926535;
}

// No need in constant.cpp

Is this the best way?


回答1:


I'd say:

-- In c++14:

namespace constant 
{
  template <typename T = double>
  constexpr T PI = T(3.1415926535897932385);
}

-- In c++11:

namespace constant 
{
  constexpr double PI = 3.1415926535897932385;
}

-- In c++03 :

namespace constant 
{
  static const double PI = 3.1415926535897932385;
}

Note that if your constant does not have a trivial type and you are within a shared library, i would advise to avoid giving it internal linkage at global/namespace scope, i don't know the theory about this but in practice it does tend to randomly mess things up :)



来源:https://stackoverflow.com/questions/26429374/what-is-the-best-way-to-define-a-double-constant-in-a-namespace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!