How to workaround the inconsistent definition of n

2020-06-03 01:30发布

The numeric_limits traits is supposed to be a general way of obtaining various type infomation, to be able to do things like

template<typename T>
T min(const std::vector<T>& vect)
{
    T val = std::numeric_limits<T>::min();

    for(int i=0 ; i<vect.size() ; i++)
        val = max(T, vect[i]);

    return val;
}

The problem is that (at least using MS Visual Studio 2008) numeric_limits<int>::min() returns the smallest negative number, while numeric_limits<double>::min() returns the smallest positive number!

Anyone knows the rationalie behind this design? Is there a better (recommended?) way of using numeric_limits? In my specific function above, I could of course initialize T to vect[0], but that is not the answer I am looking for..

See also (floating-point-specific) discussion here

7条回答
仙女界的扛把子
2楼-- · 2020-06-03 02:33

You can use Boost libraries. The library Numeric Conversions provides a class called bounds that can be used consistently.

See the documentation here.

查看更多
登录 后发表回答