static_cast有界类型

Jyh*_*ess 3 c++

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

例如:

int i = 70000;
short s = static_cast<short>(i);
std::cout << "s=" << s << std::endl;
Run Code Online (Sandbox Code Playgroud)

将显示:

s=4464
Run Code Online (Sandbox Code Playgroud)

我需要一个能够使用类型限制的"智能"转换,在这种情况下返回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);
}
Run Code Online (Sandbox Code Playgroud)

这个函数适用于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();
  }
}
Run Code Online (Sandbox Code Playgroud)

Pon*_*gge 5

看一下boost的数字转换库.我认为你需要定义一个溢出策略,将源值截断到目标的合法范围(但我还没有尝试过).总之,它可能需要比上面的示例更多的代码,但如果您的需求发生变化,则应该更加强大.