#include <compare>
struct A
{
int n;
auto operator<=>(A const& other) const
{
if (n < other.n)
{
return std::strong_ordering::less;
}
else if (n > other.n)
{
return std::strong_ordering::greater;
}
else
{
return std::strong_ordering::equal;
}
}
// compile error if the following code is commented out.
// bool operator==(A const& other) const
// { return n == other.n; }
};
int main()
{
A{} == A{};
}
Run Code Online (Sandbox Code Playgroud)
看在线演示
为什么我必须 operator == 在 足够的时候提供operator <=> ?
c++ language-design language-lawyer spaceship-operator c++20
我<=>在C ++ 20中使用新的宇宙飞船运算符遇到一种奇怪的行为。我正在将Visual Studio 2019编译器与一起使用/std:c++latest。
这段代码可以正常编译:
#include <compare>
struct X
{
int Dummy = 0;
auto operator<=>(const X&) const = default; // Default implementation
};
int main()
{
X a, b;
a == b; // OK!
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我将X更改为:
struct X
{
int Dummy = 0;
auto operator<=>(const X& other) const
{
return Dummy <=> other.Dummy;
}
};
Run Code Online (Sandbox Code Playgroud)
我收到以下编译器错误:
error C2676: binary '==': 'X' does not define this operator or a conversion to …