Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 356
user1899020 Avatar asked Oct 26 '25 12:10

user1899020


1 Answers

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 :)

like image 84
Drax Avatar answered Oct 28 '25 04:10

Drax



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!