问题描述
在C ++ 20中,新的宇宙飞船运算符< =>
导致我遇到奇怪的行为.我正在将Visual Studio 2019编译器与/std:c ++ latest
一起使用.
I'm running into a strange behavior with the new spaceship operator <=>
in C++20. I'm using Visual Studio 2019 compiler with /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;
}
但是,如果我将 X 更改为此:
However, if I change X to this:
struct X
{
int Dummy = 0;
auto operator<=>(const X& other) const
{
return Dummy <=> other.Dummy;
}
};
我收到以下编译器错误:
I get the following compiler error:
错误C2676:二进制'==':'X'未定义此运算符或未转换为预定义运算符可接受的类型
我也在clang上尝试了此操作,并且得到了类似的行为.
I tried this on clang as well, and I get similar behavior.
我希望对默认实现为何能正确生成 operator ==
而不创建自定义代码的原因进行一些解释.
I would appreciate some explanation on why the default implementation generates operator==
correctly, but the custom one doesn't.
推荐答案
这是设计使然.
3 如果类定义未明确声明 ==
运算符函数,但声明默认的三向比较运算符函数,会隐式声明 ==
运算符函数具有与三向比较运算符功能相同的访问权限.X类的隐式声明的 ==
运算符是内联的成员,并且在X的定义中定义为默认值.
3 If the class definition does not explicitly declare an ==
operator function, but declares a defaulted three-way comparisonoperator function, an ==
operator function is declared implicitlywith the same access as the three-way comparison operator function.The implicitly-declared ==
operator for a class X is an inlinemember and is defined as defaulted in the definition of X.
只有默认的< =>
允许存在合成的 ==
.理由是,像 std :: vector
这样的类不应使用非默认的< =>
进行相等性测试.对 ==
使用< =>
并不是比较向量的最有效方法.< =>
必须给出确切的顺序,而 ==
可能会通过首先比较大小来提早保释.
Only a defaulted <=>
allows a synthesized ==
to exist. The rationale is that classes like std::vector
should not use a non-defaulted <=>
for equality tests. Using <=>
for ==
is not the most efficient way to compare vectors. <=>
must give the exact ordering, whereas ==
may bail early by comparing sizes first.
如果一个类在其三向比较中做一些特殊的事情,则可能需要在其 ==
中做一些特殊的事情.因此,该语言不会产生可能不合理的默认值,而是将其留给程序员.
If a class does something special in its three-way comparison, it will likely need to do something special in its ==
. Thus, instead of generating a potentially non-sensible default, the language leaves it up to the programmer.
这篇关于非默认运算符< =>在C ++ 20中不会生成==和!=的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!