gpt4 book ai didi

c++ - 非默认运算符 <=> 在 C++20 中不会生成 == 和 !=

转载 作者:行者123 更新时间:2023-12-01 19:27:27 26 4
gpt4 key购买 nike

我遇到了新的宇宙飞船运算符(operator)的奇怪行为 <=>在 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;
}

但是,如果我将 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==正确,但自定义的则不然。

最佳答案

这是设计使然。

[class.compare.default] (emphasis mine)

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 的类不应使用非默认 <=>用于平等测试。使用<=>对于 ==不是比较 vector 的最有效方法。 <=>必须给出准确的顺序,而 ==可以通过先比较尺寸来提前退出。

如果一个类在三向比较中做了一些特殊的事情,它可能需要在其 == 中做一些特殊的事情。因此,该语言不会生成潜在的不合理的默认值,而是将其留给程序员。

关于c++ - 非默认运算符 <=> 在 C++20 中不会生成 == 和 !=,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58780829/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com