Why doesn't numeric_limits::min() return the smallest value?

后端 未结 2 1809
既然无缘
既然无缘 2021-01-05 03:19

When I run this code:

#include 
#include 

#define T double

int main()
{
    static const T val = std::numeric_limits::         


        
2条回答
  •  执笔经年
    2021-01-05 03:49

    Historical reasons. std::numeric_limits was originally built around the contents of (where you have e.g. INT_MIN) and (where you have e.g. DBL_MIN). These two files were (I suspect) designed by different people; people doing floating point don't need a separate most positive and most negative value, because the most negative is always the negation of the most positive, but they do need to know the smallest value greater than 0. Regretfully, the values have the same pattern for the name, and std::numeric_limits ended up defining the semantics of min differently depending on std::numeric_limits<>::is_integer.

    This makes template programming more awkward, you keep having to do things like std::numeric_limits::is_integer ? std::numeric_limits::min() : -std::numeric_limits::max() so C++11 adds std::numeric_limits<>::lowest(), which does exactly what you'd expect.

提交回复
热议问题