C++中三路比较运算符的具体用法
·
三路比较运算符概述
三路比较运算符(<=>)是C++20引入的新特性,用于简化比较操作。它返回一个比较类别类型的对象,可以直接表示两个对象的相对大小关系。该运算符通常与std::compare_three_way或其他比较类别类型(如std::strong_ordering)一起使用。
基本语法
三路比较运算符的语法如下:
auto operator<=>(const T& other) const = default; // 默认实现
或自定义实现:
auto operator<=>(const T& other) const {
// 自定义比较逻辑
return /* 比较结果 */;
}
比较类别类型
三路比较运算符的返回值类型是以下之一:
std::strong_ordering:表示强排序(如整数、指针)。std::weak_ordering:表示弱排序(如浮点数)。std::partial_ordering:表示部分排序(如NaN的浮点数)。
默认实现
如果类的所有成员都支持<=>,可以直接使用默认实现:
struct Point {
int x, y;
auto operator<=>(const Point&) const = default;
};
此时,编译器会自动生成==、!=、<、<=、>、>=等运算符。
自定义实现
对于需要自定义比较逻辑的情况,可以手动实现<=>:
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 ((a <=> b) == std::strong_ordering::less) {
// a < b
}
示例代码
以下是一个完整的示例:
#include <compare>
#include <iostream>
struct Point {
int x, y;
auto operator<=>(const Point&) const = default;
};
int main() {
Point a{1, 2}, b{1, 3};
if (a < b) {
std::cout << "a is less than b\n";
}
return 0;
}
注意事项
- 如果类包含不支持
<=>的成员,需要手动实现比较逻辑。 - 默认生成的
<=>会按声明顺序比较成员,直到找到第一个不相等的成员。 - 三路比较运算符通常与
= default一起使用,以减少代码冗余。
更多推荐
所有评论(0)