[英]Spaceship Operator on NaN
How does C++ treat floating-point NaN when doing space-ship comparison operations? C++在做飞船比较运算时如何处理浮点NaN? We know that the usual compares always return false, so how does this change with NaN?
我们知道通常的比较总是返回 false,那么这对 NaN 有什么影响呢?
std::numeric_limits<double>::quiet_NaN() <=> std::numeric_limits<double>::quiet_NaN()
According to cppreference , in the case of floating point arguments to the built-in <=>
operator:根据cppreference ,在浮点 arguments 到内置
<=>
运算符的情况下:
[...] the operator yields a prvalue of type
std::partial_ordering
.[...] 运算符产生
std::partial_ordering
类型的纯右值。 The expressiona <=> b
yields表达式
a <=> b
产生
std::partial_ordering::less
ifa
is less thanb
std::partial_ordering::less
如果a
小于b
std::partial_ordering::greater
if a is greater thanb
如果 a 大于
b
,则std::partial_ordering::greater
std::partial_ordering::equivalent
ifa
is equivalent tob
(-0 <=> +0
is equivalent)std::partial_ordering::equivalent
如果a
等价于b
(-0 <=> +0
等价)std::partial_ordering::unordered
(NaN<=>
anything is unordered)std::partial_ordering::unordered
(NaN<=>
任何东西都是无序的)
So, in brief, applying <=>
to a floating point value of NaN results in std::partial_ordering::unordered
.因此,简而言之,将
<=>
应用于 NaN 的浮点值会导致std::partial_ordering::unordered
。
When evaluating an expression like a <=> b == 0
or a <=> b < 0
, if either a
or b
is NaN then the whole expression returns false
, which makes sense coming from NaN's built-in behaviour ( source ).在评估像
a <=> b == 0
或a <=> b < 0
这样的表达式时,如果a
或b
是 NaN,则整个表达式返回false
,这从 NaN 的内置行为( source )中是有意义的。 Of course, std::partial_ordering::unordered == std::partial_ordering::unordered
holds true or else this type wouldn't be very useful.当然,
std::partial_ordering::unordered == std::partial_ordering::unordered
成立,否则这种类型不会很有用。
If you can otherwise guarantee the absence of pathological floating point values, take a look at this Q/A for a floating point wrapper whose comparisons yield std::strong_ordering
.如果您可以以其他方式保证不存在病态浮点值,请查看此 Q/A以获得浮点包装器,其比较产生
std::strong_ordering
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.