How to workaround the inconsistent definition of numeric_limits::min()?

前端 未结 7 1387
予麋鹿
予麋鹿 2021-02-08 00:05

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

template
T min(con         


        
7条回答
  •  南笙
    南笙 (楼主)
    2021-02-08 00:30

    I'm not sure of the rationale but it is expected behaviour. Well, in the sense that is how Josuttis (and, presumably the standard) describes it!

    min(): "Miniumum finite value (minimum normalized value for floating-point types with denormalization)."

    As best I can tell if the type is not an integer (numeric_limits<>::is_integer) and has denormalization (numeric_limits<>::has_denorm) min() will return the smallest representable value by that type. Otherwise it will return the smallest value - which may be negative.

    For a more consistent interface check out the Boost numeric/conversion library. Specifically the bounds traits class. Here's a snippet:

    cout << "lowest float:" << boost::numeric::bounds::lowest();
    cout << "lowest int:  " << boost::numeric::bounds::lowest();
    

    You may also find the boost::integer library useful. It brings some of C99's integer support (like int_least16_t) to C++ and can help select the best sized type for you particular need. An example:

    boost::uint_t<20>::fast fastest20bits; // fastest unsigned integer that 
                                           // can hold at least 20 bits.
    boost::int_max_value_t<100000>::least  // smallest integer that can store
                                           // the value 100000.
    

    I often find that when I need one of boost::numeric/conversion or boost::integer I need them both.

提交回复
热议问题