在命名空间中定义双常数的最好方法是什么? [英] What is the best way to define a double constant in a namespace?

查看:101
本文介绍了在命名空间中定义双常数的最好方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在命名空间中定义双常数的最好方法是什么?例如

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

这是最好的方法吗?

推荐答案

我会说:

- 在c ++ 14中:

-- In c++14:

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

- 在c ++ 11中:

-- In c++11:

namespace constant 
{
  constexpr double PI = 3.1415926535897932385;
}

- 在c ++ 03中:

-- In c++03 :

namespace constant 
{
  static const double PI = 3.1415926535897932385;
}






请注意,没有一个琐碎的类型,你在一个共享库,我会建议避免给它内部链接在全局/命名空间范围,我不知道这个理论,但在实践中,它往往随机混乱的东西:)


Note that if your constant does not a 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 :)

这篇关于在命名空间中定义双常数的最好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆