为什么我可以使用默认的<=>而不是用户提供的默认值调用==?

时间:2020-04-05 08:26:50

标签: c++ comparison standards c++20 spaceship-operator

#include <compare>

struct A
{
    int n;
    auto operator <=>(const A&) const noexcept = default;
};

struct B
{
    int n;
    auto operator <=>(const B& rhs) const noexcept
    {
        return n <=> rhs.n;
    }
};

int main()
{
    A{} == A{}; // ok
    B{} == B{}; // error: invalid operands to binary expression
}

使用clang-10作为clang -std=c++20 -stdlib=libc++ main.cpp

编译

为什么A{} == A{}起作用但B{} == B{}不起作用?

1 个答案:

答案 0 :(得分:9)

在太空飞船运营商的原始设计中,允许==调用<=>,但是由于效率方面的考虑,后来不允许这样做(<=>通常是实现{ {1}})。 ==仍被定义为隐式定义operator<=>() = default,为了方便起见,该成员正确调用了成员上的operator==而不是==。所以你想要的是这个

<=>

请注意,您可以独立地默认struct A { int n; auto operator<=>(const A& rhs) const noexcept = default; }; // ^^^ basically expands to vvv struct B { int n; bool operator==(const B& rhs) const noexcept { return n == rhs.n; } auto operator<=>(const B& rhs) const noexcept { return n <=> rhs.n; } }; ,同时仍提供用户定义的operator==

operator<=>