user1899020
user1899020

Reputation: 13575

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?

Upvotes: 4

Views: 1536

Answers (1)

Drax
Drax

Reputation: 13278

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

Upvotes: 6

Related Questions