相关疑难解决方法(0)

使用boost :: numeric_cast <>

当我想在不同的整数类型之间进行转换时,似乎最好的语法是使用boost::numeric_cast<>():

int y = 99999;
short x = boost::numeric_cast<short>(y); // will throw an exception if y is too large
Run Code Online (Sandbox Code Playgroud)

我从来没用过那个; 但是语法非常简单,所以一切都很顺利.

现在假设我想做一些更高级的事情:我希望它能够返回目标类型的最小值或最大值(饱和度),而不是抛出异常.我无法想出一种表达方式,但文档表明它是可能的(可能使用RawConverter策略).所有我能想到的是以下丑陋:

short x = numeric_cast<short>(max(min(y, SHORT_MAX), SHORT_MIN);
Run Code Online (Sandbox Code Playgroud)

那么我怎么能用boost来表达"饱和的演员" numeric_cast呢?

c++ boost type-conversion

14
推荐指数
1
解决办法
6434
查看次数

标签 统计

boost ×1

c++ ×1

type-conversion ×1