spaceship operator由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); }
// ... non-comparisonfunctions ...
};
将被替换为:
class Point
{
int x;
int y;
public:
auto operator<=>(const Point &) const = default;
// ... non-comparison functions ...
};
因此,为了回答您的问题,operator<=>作为类成员重载允许您对类对象使用所有比较运算符,而不必实现它们,默认它也是 defaults operator==,如果它没有另外声明,它在术语中自动实现operator!=,使所有比较操作都可用一个表达式。此功能是主要用例。
我想指出,如果不引入与 C++20的默认比较功能,那么宇宙飞船运算符是不可能的。
默认三向比较
[...]
LetR为返回类型,每对 subobjectsa的b比较如下:
[...]
... 如果R是std::strong_ordering,则结果为:
a == b ? R::equal : a < b ? R::less : R::greater
否则,如果R是std::weak_ordering,则结果为:
a == b ? R::equivalent : a < b ? R::less : R::greater
否则 ( Ris std::partial_ordering),结果为:
a == b ? R::equal : a < b ? R::less : b < a ? R::greater : R::unordered
根据任何重载的规则operator<=>,默认<=>重载还允许将类型与<、<=、>和进行比较>=。
如果operator<=>默认并且operator==根本没有声明,则operator==隐式默认。
它还允许operator ==仅默认,这将实现operator !=,尽管不像前者那样通用,但它也是一个有趣的可能性。