为什么太空飞船操作员的行为不符合预期?

问题描述 投票:5回答:1
#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编译

为什么宇宙飞船操作员的行为不符合预期?

c++ comparison standards c++20 spaceship-operator
1个回答
4
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.