当我想在不同的整数类型之间进行转换时,似乎最好的语法是使用 boost::numeric_cast<>()
:
int y = 99999;
short x = boost::numeric_cast<short>(y); // will throw an exception if y is too large
我从来没有用过;但是语法非常简单,所以一切都很好。
现在假设我想做一些更高级的事情:我希望它返回目标类型的最小值或最大值(饱和度),而不是抛出异常。我想不出一种表达方式,但是 documentation表明这是可能的(可能使用 RawConverter
策略)。我能想到的只是以下丑陋的:
short x = numeric_cast<short>(max(min(y, SHORT_MAX), SHORT_MIN);
那么如何使用 boost 的 numeric_cast
来表达“饱和类型转换”? ?
最佳答案
你可能会这样做:
#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)。
这样您就可以让 Boost 的 numeric_cast
确定该值是否超出范围,然后可以做出相应的 react 。
关于c++ - 使用 boost::numeric_cast<>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4424168/