【问题标题】:static_cast with bounded types有界类型的 static_cast
【发布时间】:2011-08-24 20:05:45
【问题描述】:

当您使用经典的 static_cast(或 c 强制转换)将 int 转换为 short 时,如果该值超出了 short 限制,编译器将截断该 int。

例如:

int i = 70000;
short s = static_cast<short>(i);
std::cout << "s=" << s << std::endl;

将显示:

s=4464

我需要一个能够使用类型限制的“智能”转换,在这种情况下返回 32767。类似的东西:

template<class To, class From>
To bounded_cast(From value)
{
  if( value > std::numeric_limits<To>::max() )
  {
    return std::numeric_limits<To>::max();
  }
  if( value < std::numeric_limits<To>::min() )
  {
    return std::numeric_limits<To>::min();
  }
  return static_cast<To>(value);
}

此函数适用于 int、short 和 char,但需要一些改进才能适用于 double 和 float。

但这不是轮子的再发明吗?

你知道现有的图书馆可以做到这一点吗?

编辑:

谢谢。我找到的最佳解决方案是这个:

template<class To, class From>
To bounded_cast(From value)
{
  try
  {
    return boost::numeric::converter<To, From>::convert(value);
  }
  catch ( const boost::numeric::positive_overflow & )
  {
    return std::numeric_limits<To>::max();
  }
  catch ( const boost::numeric::negative_overflow & )
  {
    return std::numeric_limits<To>::min();
  }
}

【问题讨论】:

  • 你不应该把答案放在你原来的问题中。但是,您可以发布自己问题的答案。我鼓励你把你的编辑从你的问题中去掉,然后把它放在一个答案中。

标签: c++


【解决方案1】:

看看 boost 的Numeric Conversion library。我认为您需要定义一个 overflow policy 将源值截断到目标的合法范围(但我没​​有尝试过)。总而言之,它可能需要比您上面的示例更多的代码,但如果您的需求发生变化,应该会更加健壮。

【讨论】:

    【解决方案2】:

    阅读Boost numeric_cast<> with a default value instead of an exception?所以问题。

    您可以在抛出异常时使用 std::numeric_list 作为默认值

    【讨论】:

      猜你喜欢
      • 2017-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多