为什么我可以使用默认的< =>调用==但不是用户提供的? [英] 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
compiled with clang-10 as clang -std=c++20 -stdlib=libc++ main.cpp
为什么 A {} == A {}
工作,但不是 B {} == B {}
?
推荐答案
在飞船运算符的原始设计中,允许 ==
调用< ; =>
,但是后来出于效率考虑而被禁止使用(< =>
通常是实现 ==
)。 operator< =>()=默认值
仍被定义为隐式定义 operator ==
,它会正确调用<$为方便起见,在成员上使用c $ c> == 代替< =>
。因此,您想要的是这样:
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;
}
};
请注意,您可以独立地默认 operator ==
,同时仍提供用户定义的 operator< =>
:
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;
}
};
这篇关于为什么我可以使用默认的< =>调用==但不是用户提供的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!