Are there any C++11 constexpr
constants which can be used instead of the constant macros from <cmath>
, i.e. constants like M_PI
and friends? Or lacking that, any global const
values which provide these constants at runtime?
Asked
Active
Viewed 2,354 times
4

MvG
- 57,380
- 22
- 148
- 276
-
What benefit would `constexpr` make? The macros are constant expressions, no? – Pubby Mar 22 '13 at 19:37
-
1@Pubby: `constexpr` vs. macro: main benefit would be clean namespace handling, and the fact that issues like [this one](http://stackoverflow.com/q/6563810/1468366) were perhaps less likely. `constexpr` vs. simple `const`: one could be sure to use them at compile time, e.g. to compute template arguments. – MvG Mar 22 '13 at 19:41
1 Answers
5
There are no predefined constexpr or global const constants defined in C++ standard library. But you can define them by yourself like, for example:
namespace MathConstants {
const double E = 2.71828182845904523536;
const double LOG2E = 1.44269504088896340736;
const double LOG10E = 0.434294481903251827651;
const double LN2 = 0.693147180559945309417;
const double LN10 = 2.30258509299404568402;
const double PI = 3.14159265358979323846;
const double PI_2 = 1.57079632679489661923;
const double PI_4 = 0.785398163397448309616;
const double PI_1_PI = 0.318309886183790671538;
const double PI_2_PI = 0.636619772367581343076;
const double PI_2_SQRTPI = 1.12837916709551257390;
const double SQRT2 = 1.41421356237309504880;
const double SQRT1_2 = 0.707106781186547524401;
};
Or use boost math constant templates, some documentation here (haven't used it).
-
1+1 for the boost pointer. Seems like in recent versions the stuff has been moved out of the internals subpackage, so its API should be reasonably stable. See [recent documentation](http://www.boost.org/doc/libs/1_53_0/libs/math/doc/sf_and_dist/html/math_toolkit/constants.html). – MvG Mar 23 '13 at 01:30