【发布时间】:2010-12-12 21:34:55
【问题描述】:
当我想在不同的整数类型之间进行转换时,似乎最好的语法是使用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 来表达“饱和演员表”?
【问题讨论】:
标签: c++ boost type-conversion