Reputation: 528
I'm currently getting into more C++11 stuff and jumped about constexpr
. In one of my books it's said that you should use it for constants like π for example in this way:
#include <cmath>
// (...)
constexpr double PI = atan(1) * 4;
Now I wanted to put that in an own namespace, eg. MathC
:
// config.h
#include <cmath>
namespace MathC {
constexpr double PI = atan(1) * 4;
// further declarations here
}
...but here IntelliSense says function call must have a constant value in a constant expression
.
When I declare PI
the following way, it works:
static const double PI = atan(1) * 4;
What is the actual reason the compiler doesn't seem to like constexpr
but static const
here? Shouldn't constexpr
be eligible here, too, or is it all about the context here and constexpr
shouldn't be declared outside of functions?
Thank you.
Upvotes: 2
Views: 1031
Reputation: 206717
What is the actual reason the compiler doesn't seem to like
constexpr
butstatic const
here?
A constexpr
must be evaluatable at compile time while static const
does not need to be.
static const double PI = atan(1) * 4;
simply tells the compiler that PI
may not be modified once it is initialized but it may be initialized at run time.
Upvotes: 5