三路比较运算符()简化C++20中类类型的比较,自动推导大小关系并返回std::strong_ordering等类型;基本用法如int比较所示,自定义类可默认生成或手动实现operator,按成员顺序逐个比较;手动实现时可通过if(auto cmp = ...; cmp != 0)优化逻辑;定义后编译器自动生成==、!=、=,但建议单独定义operator==以提升性能;整体减少样板代码,提升安全性与简洁性。

在C++20中,三路比较运算符(),也被称为“太空船运算符”(spaceship operator),可以简化类类型的比较操作。它能自动推导出两个对象之间的大小关系,返回一个比较类别类型,比如 std::strong_ordering、std::weak_ordering 或 std::partial_ordering。
基本语法与返回值
三路比较运算符的返回值表示比较结果:
-
a b返回负值:a 小于 b -
a b返回 0:a 等于 b -
a b返回正值:a 大于 b
常见使用方式如下:
#include#include int main() { int x = 5, y = 3; auto result = x <=> y; if (result > 0) { std::cout << "x > y\n"; } else if (result < 0) { std::cout << "x < y\n"; } else { std::cout << "x == y\n"; } return 0; }
自定义类型的默认三路比较
对于自定义类,如果所有成员都支持 ,可以使用 = default 自动生成比较操作。
立即学习“C++免费学习笔记(深入)”;
#include#include struct Point { int x; int y; // 自动生成三路比较 auto operator<=>(const Point&) const = default; }; int main() { Point a{1, 2}, b{1, 3}; if (a < b) std::cout << "a < b\n"; if (a <= b) std::cout << "a <= b\n"; if (a != b) std::cout << "a != b\n"; return 0; }
编译器会逐个成员按声明顺序比较,相当于先比 x,再比 y。
手动实现三路比较
如果需要自定义逻辑,也可以手动实现 operator。
struct Person {
std::string name;
int age;
auto operator<=>(const Person& other) const {
if (auto cmp = name <=> other.name; cmp != 0)
return cmp;
return age <=> other.age;
}
};
上面的例子先比较名字,名字相等时再比较年龄。利用 if (auto cmp = ...; cmp != 0) 可以提前返回非零结果。
与普通比较操作符的关系
C++20 中,只要定义了 operator,编译器就能自动生成 ==、!=、、、>、>= 的行为。
但注意:operator== 不参与三路比较,建议单独定义以提高效率(特别是对容器或字符串)。
bool operator==(const Person& other) const {
return name == other.name && age == other.age;
}
基本上就这些。三路比较减少了样板代码,让类的比较更简洁安全。只要成员支持比较,用 = default 是最省事的方式。手动实现时注意比较顺序和返回类型即可。不复杂但容易忽略细节。










