gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 12:41:50 26 4
gpt4 key购买 nike

#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++ - 为什么我可以使用默认的 <=> 而不是用户提供的调用 ==?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61039897/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com