首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么可以使用默认的<=>调用==,而不能使用用户提供的user?

为什么可以使用默认的<=>调用==,而不能使用用户提供的user?
EN

Stack Overflow用户
提问于 2020-04-05 16:26:51
回答 1查看 162关注 0票数 7
代码语言:javascript
复制
#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{}不能工作

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-05 16:30:34

在宇宙飞船操作员的原始设计中,==被允许调用<=>,但后来由于效率问题而被禁止(<=>通常是实现==的一种低效方式)。为方便起见,operator<=>() = default仍被定义为隐式定义operator==,它正确地调用成员上的==而不是<=>。所以你想要的是:

代码语言:javascript
复制
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==

代码语言:javascript
复制
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;
    }
};
票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61039897

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档