c++之为什么我可以使用默认的 => 而不是用户提供的调用 ==

me-sa 阅读:27 2025-02-15 21:57:57 评论:0

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

请您参考如下方法:

在飞船运算符(operator)的原始设计中,==允许调用<=> ,但后来由于效率问题而被禁止(<=> 通常是实现 == 的低效方式)。 operator<=>() = default仍被定义为隐式定义 operator== ,正确调用 ==而不是 <=>在成员(member)上,为了方便。所以你想要的是这样的:

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


标签:C++
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号