【发布时间】:2015-05-11 01:44:40
【问题描述】:
我正在寻找一个标准库或 Boost 函数,它可以将一个数字无损地转换为另一种原始类型,并以某种方式通知我该转换是否是无损的(如果不是,则抛出异常)。以下是一些示例:
auto x = lossless_cast<double>(1u); // ok, double can represent 1
auto x = lossless_cast<int>(1.2); // fail, int can't represent 1.2
auto x = lossless_cast<int>(1E200); // fail, int can't represent 1E200
boost::numeric_cast 很接近,因为它会拾取超出目标类型数值范围的强制转换,但如果它们是无损的,但在目标类型中则不会(参见我的第二个示例)。
有一个SO question for the C language which provides some hand-rolled solutions to this problem,但我追求的是boost或标准库解决方案,基本上具有以下功能:
template <typename out, typename in>
out lossless_cast(in in_value)
{
out out_value = static_cast<out>(in_value);
if (static_cast<in>(out_value) != in_value)
throw; // some exception
return out_value;
}
这个功能存在吗?
【问题讨论】:
-
编写一个函数来执行转换,然后比较之前和之后的相等性。
-
如果您期待一个没有演员往返的解决方案,这可能是一个比您意识到的更难的问题。例如,
float不能代表 16,777,217。 -
@IgorTandetnik:这不是一个好主意 - 在某些情况下会产生 未定义的行为(例如问题中的
lossless_cast<int>(1E200);案例)。 -
有趣的是 double 也不能无损地表示
1.2.... ;) -
谁能结束这个问题,请再读一读我的问题。这不是那个问题的重复。