c++ - 使用 boost::numeric_cast<>

标签 c++ boost type-conversion

当我想在不同的整数类型之间进行转换时,似乎最好的语法是使用 boost::numeric_cast<>() :

int y = 99999;
short x = boost::numeric_cast<short>(y); // will throw an exception if y is too large

我从来没有用过;但是语法非常简单,所以一切都很好。

现在假设我想做一些更高级的事情:我希望它返回目标类型的最小值或最大值(饱和度),而不是抛出异常。我想不出一种表达方式,但是 documentation表明这是可能的(可能使用 RawConverter 策略)。我能想到的只是以下丑陋的:

short x = numeric_cast<short>(max(min(y, SHORT_MAX), SHORT_MIN);

那么如何使用 boost 的 numeric_cast 来表达“饱和类型转换”? ?

最佳答案

你可能会这样做:

#include <limits>

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

(对于支持它的类型,错误情况也可能返回 -inf/+inf)。

这样您就可以让 Boost 的 numeric_cast 确定该值是否超出范围,然后可以做出相应的 react 。

关于c++ - 使用 boost::numeric_cast<>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4424168/

相关文章:

c++ - 什么时候应该使用直接初始化,什么时候应该使用复制初始化?

c++ - 尝试使用 switch 和 if 语句创建日历来检查用户输入然后输出日期

c++ - 递归地 boost 分割并附加到集合

javascript - JSLint 错误 "Bad type."是什么意思?

c++ - 如果你有两个同名函数(重载),并且有一个转换构造函数,转换构造函数会被调用吗?

c++ - 如何测量 STL 容器的总内存消耗?

C++代码优雅

c++ - 如何将字节数组转换为 boost::multiprecision::uint128_t?

c++ - boost spirit 莱克斯和气。集成跳过解析器

java - double 到 int 的转换