Using boost::numeric_cast<>

后端 未结 3 406
盖世英雄少女心
盖世英雄少女心 2021-01-08 00:11

When I want to convert between different integer types, it seems the best syntax is to use boost::numeric_cast<>():

int y = 99999;
short x         


        
3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-08 00:46

    You could probably do something like this:

    #include 
    
    template
    Target saturation_cast(Source src) {
       try {
          return boost::numeric_cast(src);
       }
       catch (const boost::negative_overflow &e) {
          return std::numeric_limits::lowest();
          /* Or, before C++11:
          if (std::numeric_limits::is_integer)
             return std::numeric_limits::min();
          else
             return -std::numeric_limits::max();
          */
       }
       catch (const boost::positive_overflow &e) {
          return std::numeric_limits::max();
       }
    }
    

    (For types that support it the error cases could also return -inf/+inf).

    This way you let Boost's numeric_cast determine if the value is out of bounds and can then react accordingly.

提交回复
热议问题