comparable<>接口
时间: 2023-10-15 09:08:28 浏览: 48
`std::comparable` 是 C++20 引入的一个新概念,它是一个可以用于比较两个对象的接口,类似于 `std::equality_comparable` 接口。
通过实现 `std::comparable`,我们可以定义一个类型,使其能够在各种算法和容器中进行排序、查找等操作。这个接口包括三个比较运算符:`<`、`>` 和 `<=`,其余比较运算符可以通过这三个运算符进行推导得到。
以下是一个示例:
```c++
#include <compare>
class MyType {
public:
int value;
// 定义 “<=>” 运算符
auto operator<=>(const MyType&) const = default;
// 自定义构造函数
MyType(int v) : value(v) {}
// 自定义输出函数
friend std::ostream& operator<<(std::ostream& os, const MyType& obj) {
os << obj.value;
return os;
}
};
int main() {
MyType a(10), b(20);
if (a < b) {
std::cout << a << " is less than " << b << std::endl;
} else {
std::cout << a << " is greater than or equal to " << b << std::endl;
}
return 0;
}
```
在上面的示例中,我们通过 `operator<=>` 运算符来实现 `std::comparable` 接口,然后就可以在 `main` 函数中使用 `<` 运算符来比较两个对象了。
需要注意的是,`operator<=>` 运算符必须是一个成员函数,且返回值类型必须是 `std::strong_ordering`、`std::weak_ordering` 或 `std::partial_ordering` 之一,这些类型都是 C++20 新增的用于比较的强弱关系枚举类型。