c++ - 三向比较取代了除 == 之外的所有其他比较运算符?
问题描述
在 g++ 10 中,我尝试使用三向比较,仅用于实验。
我读到不再需要其他运算符(== 除外)。
但即使我可以使用运算符(它在编译器上实现),它也不会取代(或暗示)!=。
因此,以下代码不起作用。
#include<iostream>
using namespace std;
struct A
{
struct Iterator
{
size_t index;
size_t operator*() { return index + 1000; }
//bool operator!=(const Iterator &a) const { return index != a.index; }
auto operator<=>(const Iterator &a) const { return index <=> a.index; }
Iterator &operator++() { ++index; return *this; }
};
Iterator begin() { return Iterator{0}; }
Iterator end() { return Iterator{5}; }
};
int main()
{
A a;
auto result = a.begin() <=> a.end();
for (auto b : a)
cout << b << "\n";
cout << (a.begin() != a.end()) << "\n";
return 0;
}
我在这里想念什么?
解决方案
我读到不再需要其他运算符(== 除外)。
对,除了 ==
关键位。比较运算符有两类:
- 等式运算符 (
==
,!=
) - 排序运算符 (
<=>
,<
,>
,<=
,>=
)
在每个类别中,我列出的第一个 (==
和<=>
) 是主要的比较运算符。如果要选择加入该类别,它是唯一需要定义的运算符。如果您想要平等,请提供==
. 如果您想订购,请提供<=>
(以及==
)。其他比较运算符是辅助比较运算符 - 使用辅助比较的表达式在 C++20 中被重写为使用主比较运算符。
这些类别是完全不同的† - 没有交叉。x != y
表达式可以调用,operator==(x, y)
甚至可以调用,operator==(y, x)
但它永远不会调用operator<=>
任何类型的 an。
您的代码需要相等比较,但没有定义相等运算符,因此它的格式不正确。要使其正常工作,您需要添加:
bool operator==(const Iterator &a) const { return index == a.index; }
auto operator<=>(const Iterator &a) const { return index <=> a.index; }
注意==
,不是!=
。你不应该在 C++20 中声明二级比较运算符,除非你对它们有非常特殊的需要(这不是这样的需要)。
有关更多信息,请参阅C++20 中的比较。
†此规则的唯一例外是,为方便起见,如果您默认 operator<=>
,那么您还会得到一个声明的 defaulted operator==
。就好像你自己都违约了。在此示例中,由于您的比较只是默认的成员比较,您可以编写:
auto operator<=>(const Iterator &a) const = default;
作为你的单一比较运算符声明,它的行为就像你写的一样:
bool operator==(const Iterator &a) const = default;
auto operator<=>(const Iterator &a) const = default;
这为您提供了程序所需的正确相等运算符。
推荐阅读
- flutter - 其他文件中的单独小部件颤动
- android - Rx Java observable 没有发出正确的状态执行一次,初始值传递给折叠
- java - 监控 Java melody jdbc 连接
- python - 百分位数必须在 [0, 100] 范围内
- javascript - 更新插槽 vuejs 中的数据
- ionic4 - 如何解决离子,图标不显示在应用程序中的问题
- java - maven-compiler-plugin:3.8.1:compile throwing NullPointerException
- javascript - 为什么单击一行时我的表格没有响应
- perl - Perl 模块 Mail::POP3Client 和 Net::Pop3 不适用于 pop.gmail.com 或 pop.aol.com
- c - 单个 UDP 数据报中的 RTP 数据包数