使用boost :: numeric_cast<> [英] Using boost::numeric_cast<>

查看:265
本文介绍了使用boost :: numeric_cast<>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 = boost::numeric_cast<short>(y); // will throw an exception if y is too large

我从来没有使用的;然而,语法是pretty简单易懂,所以一切都很好。

I have never used that; however the syntax is pretty straightforward, so all is well.

现在假设我希望做一些更高级的:不是抛出一个异常,我想它返回目标类型(饱和度)的最小或最大。我无法想出一个办法来恩preSS的,但是的文档表明,它是可能的(可能使用 RawConverter 策略)。所有我能想出如下丑:

Now suppose I want to do something a bit more advanced: instead of throwing an exception, I'd like it to return the min or max of the target type (saturation). I couldn't figure out a way to express that, but the documentation suggests that it is possible (probably using RawConverter policy). All I could come up with is the following ugly:

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

所以,我怎么能前preSS饱和投使用boost的 numeric_cast

推荐答案

您也许可以做这样的事情:

You could probably do something like this:

#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)。

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

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

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

这篇关于使用boost :: numeric_cast&LT;&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆