#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{}不能工作
发布于 2020-04-05 16:30:34
在宇宙飞船操作员的原始设计中,==被允许调用<=>,但后来由于效率问题而被禁止(<=>通常是实现==的一种低效方式)。为方便起见,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;
}
};https://stackoverflow.com/questions/61039897
复制相似问题