Why can I invoke == with a defaulted <=> but not a user-provided one?

后端 未结 1 1522
情深已故
情深已故 2021-01-05 08:54
#include 

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

struct B
{
    int n;
    auto operator <=         


        
相关标签:
1条回答
  • 2021-01-05 09:46

    In the original design of the spaceship operator, == is allowed to call <=>, but this is later disallowed due to efficiency concerns (<=> is generally an inefficient way to implement ==). operator<=>() = default is still defined to implicitly define operator==, which correctly calls == instead of <=> on members, for convenience. So what you want is this:

    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;
        }
    };
    

    Note that you can independently default operator== while still providing a user-defined 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;
        }
    };
    
    0 讨论(0)
提交回复
热议问题