Question

Why, in the template class std::numeric_limits in C++, is digits (and others) defined as a (static const) field of the class, but min() and max() are methods, since these methods just return a litteral value ?

Thanks in advance.

Was it helpful?

Solution

It is not allowed to initialize a non integral constant (eg: floating point) in a class body. In C++11 the declaration changed to

...
static constexpr T min() noexcept;
static constexpr T max() noexcept;
...

To retain compatibility to C++98 the functions are kept, I think.

Example:

struct X {
    // Illegal in C++98 and C++11
    // error: ‘constexpr’ needed for in-class initialization
    //        of static data member ‘const double X::a’
    //        of non-integral type
    //static const double a = 0.1;

    // C++11
    static constexpr double b = 0.1;
};

int main () {
    std::cout << X::b << std::endl;
    return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top