首页 > 解决方案 > 三向比较取代了除 == 之外的所有其他比较运算符?

问题描述

在 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++c++20spaceship-operator

解决方案


我读到不再需要其他运算符(== 除外)。

对,除了 ==关键位。比较运算符有两类:

  • 等式运算符 ( ==, !=)
  • 排序运算符 ( <=>, <, >, <=, >=)

在每个类别中,我列出的第一个 (==<=>) 是主要的比较运算符。如果要选择加入该类别,它是唯一需要定义的运算符。如果您想要平等,请提供==. 如果您想订购,请提供<=>(以及==)。其他比较运算符是辅助比较运算符 - 使用辅助比较的表达式在 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;

这为您提供了程序所需的正确相等运算符。


推荐阅读