【发布时间】:2020-06-26 02:34:24
【问题描述】:
在 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;
}
我在这里错过了什么?
【问题讨论】:
-
您知道吗,您总是在
begin和end函数中返回一个新对象? -
@NutCracker 是的。对于这么小的东西,这不是一笔交易。
-
@NutCracker 迭代器应该是轻量级的,按值返回是
begin()和end()通常的实现方式。 -
@Chameleon 我相信你也需要包含
<compare>。否则,如果我理解规范,程序是不正确的。正确......也许不是......我被困在这里:eel.is/c++draft/expr.spaceship#9
标签: c++ c++20 spaceship-operator