Three-way Comparison =

含义

C++ 20 加入了 <=> 操作符,该操作符会按布局顺序比较成员,比较时会递归使用 <=> 操作符。对于类类型来说,即便默认的 <=> 操作符可用,也必须显式声明为 = default,否则不能使用。

如果需要在 B 类中包含 A 类,同时声明 B 类的默认 <=> 操作符以便比较 B 类对象,则必须同时在 A 类中声明默认的 <=> 操作符。

Three-way comparison operator 的返回值可以是偏序、弱序或强序。体现在 C++ 语言中是:

  • 偏序:弱序 或者 不可比较。
  • 弱序:a 和 b 的关系只能是小于、等于、大于之一。比较相等性时常用 !(a < b) && !(b < a) 的形式。相等的值可以拥有不同的身份。
  • 强序:a 和 b 的关系只能是小于、等于、大于之一。可以直接用 == 比较相等性,相等则意味着完全一致,可以相互替代。

https://news.ycombinator.com/item?id=20550902

In a strong ordering, two objects can only by one smaller, equal or larger than the other. If they are equal, it means that they are substitutable.

In a weak ordering, two objects can only be one smaller, equivalent or larger than the other. No substitutability is implied.

In a partial ordering, two objects can be one smaller, equivalent or larger than the other, or just not comparable. Again, no substitutability is implied.

默认 <=> 存在的条件

https://en.cppreference.com/w/cpp/language/default_comparisons

对引用类型成员的处理

当类中包含类型为引用的成员时,该类默认的 <=> 被删除(而不是被隐藏),除非人为定义否则不能被用户使用。

尽管“提出类类型作为模板参数”的论文使用 <=> 的规则描述类 NTTP 的要求,并建议禁用那些带有引用成员的类作为参数,但实际上 gcc 会使用地址比较允许这样的类型。