I would like to define inside a class a constant which value is the maximum possible int. Something like this:
class A
{
...
static const int ERROR_VALUE = std::numeric_limits<int>::max();
...
}
This declaration fails to compile with the following message:
numeric.cpp:8: error: ‘std::numeric_limits::max()’ cannot appear in a constant-expression
numeric.cpp:8: error: a function call cannot appear in a constant-expression
I understand why this doesn’t work, but two things look weird to me:
-
It seems to me a natural decision to use the value in constant expressions. Why did the language designers decide to make max() a function thus not allowing this usage?
-
The spec claims in 18.2.1 that
For all members declared static const in the numeric_limits template, specializations shall define these values in such a way that they are usable as integral constant expressions.
Doesn’t it mean that I should be able to use it in my scenario and doesn’t it contradict the error message?
Thank you.
While the current standard lacks support here, for integral types Boost.IntegerTraits gives you the compile time constants
const_minandconst_max.The problem arises from §9.4.2/4:
Note that it adds:
As others already mentioned
numeric_limitsmin()andmax()simply aren’t integral constant expressions, i.e. compile time constants.