C++20的宇宙飞船运算符<=>通过一行代码自动生成所有比较运算符,支持默认和自定义比较逻辑,简化类类型比较操作并减少重复代码。

在C++20中,Three-Way Comparison(也叫“宇宙飞船运算符”)<=> 让类类型的比较操作变得更简洁。它能自动生成所有常见的比较运算符(==, !=, <, <=, >, >=),减少重复代码。
如果你的类成员都支持比较,可以直接用 default 关键字让编译器自动生成 <=> 行为。
#include <iostream>
#include <compare>
struct Point {
int x;
int y;
// 自动生成三路比较
auto operator<=>(const Point&) const = default;
};
int main() {
Point a{1, 2};
Point 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;
}
只要写一行 auto operator<=>(const Point&) const = default;,就能支持所有比较操作。
有时需要自定义比较逻辑,比如优先比较某个字段。
立即学习“C++免费学习笔记(深入)”;
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;
}
};
这段代码先比较 name,如果不相等就返回结果;否则继续比较 age。<=> 返回的是一个强序类型,可以直接用于条件判断。
可以为不同但相关的类型定义比较。例如:
struct A { int value; };
struct B { int value; };
auto operator<=>(const A& a, const B& b) {
return a.value <=> b.value;
}
A a{5};
B b{10};
if (a < b) std::cout << "a < b\n"; // 成立
注意:这种非成员函数通常要声明为友元或独立函数,并包含在合适的作用域内。
如果只需要判断是否相等,可以只默认 operator==,性能更好。
struct Vec3 {
double x, y, z;
bool operator==(const Vec3&) const = default;
};
这样不会生成 <=>,但 == 和 != 都可用。其他比较操作需额外定义。
基本上就这些。宇宙飞船运算符让C++的比较更自然、更少样板代码,特别适合数据聚合类的场景。不复杂但容易忽略细节,比如返回类型用 auto 才能正确推导比较类别。
以上就是C++怎么使用C++20的Three-Way Comparison(宇宙飞船运算符)_C++代码简化与的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号