小编Jyh*_*ess的帖子

static_cast有界类型

当您使用经典的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 …
Run Code Online (Sandbox Code Playgroud)

c++

3
推荐指数
1
解决办法
1917
查看次数

标签 统计

c++ ×1