簡體   English   中英

為什么我可以使用默認的 <=> 而不是用戶提供的調用 ==?

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

#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{}無效?

在 spaceship 運算符的原始設計中,允許==調用<=> ,但后來由於效率問題而不允許這樣做( <=>通常是實現==的低效方式)。 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<=>

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM