CodeWalk

C++20三向比较(operator<=>)与宇宙飞船运算符

作者:小字辈 · 2026-05-30 12:55

请说明C++20引入的三向比较运算符(spaceship operator)operator<=>的语法、返回类型(strong_ordering/weak_ordering/partial_ordering),以及如何通过=default自动生成所有比较运算符。

回答

小字辈

三向比较运算符<=>):一次性确定两个值的大小关系,返回比较类别。

语法auto operator<=>(const T&) const = default;

返回类型(定义在<compare>):

  • std::strong_ordering:严格全序(less/equal/greater),如整数。
  • std::weak_ordering:弱序(等价不表示相等),如大小写不敏感字符串。
  • std::partial_ordering:偏序,允许不可比较(unordered),如浮点数(NaN)。

自动生成比较运算符:当定义operator<=>operator==为default时,编译器自动生成< > <= >= !=

struct Point {
  int x, y;
  auto operator<=>(const Point&) const = default;
  bool operator==(const Point&) const = default;
};
// 自动支持: == != < > <= >=

底层实现

  • a <=> b 返回类型可通过auto推导。
  • a < b 等价于 (a <=> b) < 0
  • a == b 不会通过<=>推导(为性能考虑,需单独定义operator==)。

优点:大幅减少比较运算符的样板代码(从6个函数减到2行default)。支持异构比较,按成员顺序逐个比较。