类 std::numeric_limits 中的字段与方法C++

Field vs. Method in C++ class std::numeric_limits

本文关键字:字段 方法 C++ limits std numeric      更新时间:2023-10-16

为什么在模板类std::numeric_limits C++中,digits(和其他)被定义为类的(静态常量)字段,但min()max()是方法,因为这些方法只返回一个垃圾值?

提前谢谢。

不允许在类主体中初始化非整数常量(例如:浮点数)。在C++11中,声明改为

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

我认为,为了保持与 C++98 的兼容性,这些功能被保留了。

例:

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;
}