“太空船”运算符是由Herb Sutter提出的,并被委员会采纳,将在C++20中实现。您可以
在此查看详细报告,或者如果您更喜欢观看讲座,则
在此观看该人亲自为其辩护的视频。在报告的第3/4页中,您可以看到主要用途:
需要在以下类中实现比较运算符,这是C++20之前所需的功能:
class Point
{
int x;
int y;
public:
friend bool operator==(const Point &a, const Point &b) { return a.x == b.x && a.y == b.y; }
friend bool operator<(const Point &a, const Point &b) { return a.x < b.x || (a.x == b.x && a.y < b.y); }
friend bool operator!=(const Point &a, const Point &b) { return !(a == b); }
friend bool operator<=(const Point &a, const Point &b) { return !(b < a); }
friend bool operator>(const Point &a, const Point &b) { return b < a; }
friend bool operator>=(const Point& a, const Point& b) { return !(a < b); }
};
将被替换为:
class Point
{
int x;
int y;
public:
auto operator<=>(const Point &) const = default;
};
为了回答你的问题,将
operator<=>
作为类成员重载,使你能够使用所有比较运算符来比较类对象,而无需实现它们,如果没有声明,则默认情况下也默认了
operator==
,这同时也实现了
operator!=
,使得所有比较操作都可以用单个表达式实现。这是主要的使用情况。
我想指出,在 C++20 中引入
默认比较 功能之前,
spaceship 运算符是不可能存在的。
Defaulted three-way comparison
[...]
Let R
be the return type, each pair of subobjects a
, b
is compared as follows:
[...]
... if R
is std::strong_ordering
, the result is:
a == b ? R::equal : a < b ? R::less : R::greater
Otherwise, if R
is std::weak_ordering
, the result is:
a == b ? R::equivalent : a < b ? R::less : R::greater
Otherwise (R
is std::partial_ordering
), the result is:
a == b ? R::equal : a < b ? R::less : b < a ? R::greater : R::unordered
Per the rules for any operator<=>
overload, a defaulted <=>
overload will also allow the type to be compared with <
, <=
, >
, and >=
.
If operator<=>
is defaulted and operator==
is not declared at all, then operator==
is implicitly defaulted.
另外,它也允许仅默认operator ==
,这将实现operator !=
,虽然不如前者灵活多样,但也是一个有趣的可能性。
operator<=>
(甚至在可能的情况下默认化)可以节省时间(开发和维护),而不必手动实现它们全部。另一方面,如果你想知道if( 1.1 < 2.2 )
,那么使用<=>
可能没有太多意义。 - Ted Lyngmo<=>
进行比较,还是在一般情况下使用<=>
? - Drew Dormann