Using numeric_limits::max() in constant expressions

Looks like a bit of a defect...

In C++0x, numeric_limits will have everything marked with constexpr, meaning you will be able to use min() and max() as compile-time constants.


While the current standard lacks support here, for integral types Boost.IntegerTraits gives you the compile time constants const_min and const_max.

The problem arises from §9.4.2/4:

If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions.

Note that it adds:

The member shall still be defined in a name- space scope if it is used in the program and the namespace scope definition shall not contain an initializer.

As others already mentioned numeric_limits min() and max() simply aren't integral constant expressions, i.e. compile time constants.


You want:

#include <limits>

struct A {
static const int ERROR_VALUE;
}; 

const int A::ERROR_VALUE = std::numeric_limits<int>::max();

Put the class/struct in a header and the definition in a .cpp file.