代码之家  ›  专栏  ›  技术社区  ›  xmllmx

为什么太空船操作员没有按预期行事?

  •  3
  • xmllmx  · 技术社区  · 5 年前
    #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 as一起编译 clang -std=c++20 -stdlib=libc++ main.cpp

    1 回复  |  直到 5 年前
        1
  •  4
  •   L. F.    5 年前

    在飞船操作员的最初设计中, == 允许呼叫 <=> ,但由于效率问题,这一做法后来被禁止( <=> 通常是一种低效的实现方式 ). 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<=>

    struct B {
        int n;
        // note: return type for defaulted equality comparison operator
        //       must be 'bool', not 'auto'
        bool operator==(const B& rhs) const noexcept = default;
        auto operator<=>(const B& rhs) const noexcept
        {
            return n <=> rhs.n;
        }
    };