【发布时间】:2020-03-05 22:17:16
【问题描述】:
我在 C++20 中使用新的宇宙飞船运算符 <=> 遇到了一个奇怪的行为。我正在使用带有 /std:c++latest 的 Visual Studio 2019 编译器。
此代码编译正常,符合预期:
#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;
}
但是,如果我将 X 更改为:
struct X
{
int Dummy = 0;
auto operator<=>(const X& other) const
{
return Dummy <=> other.Dummy;
}
};
我收到以下编译器错误:
error C2676: binary '==': 'X' does not define this operator or a conversion to a type acceptable to the predefined operator
我也在 clang 上试过这个,我得到了类似的行为。
我希望能解释一下为什么默认实现会正确生成operator==,而自定义实现却没有。
【问题讨论】:
-
标题使得在谷歌搜索时更难找到这个问题。也许应该改为
non-defaulted operator <=> doesn't generate == and !=。刚好遇到p1185r2后面的motivation,本来想问类似的问题自己回答。
标签: c++ c++20 spaceship-operator