【发布时间】: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++