没有为C ++ 20中的自定义太空飞船运算符实现定义等式运算符 [英] Equality operator does not get defined for a custom spaceship operator implementation in C++20

查看:100
本文介绍了没有为C ++ 20中的自定义太空飞船运算符实现定义等式运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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:

error C2676: binary '==': 'X' does not define this operator or a conversion to a type acceptable to the predefined operator

我也在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.

推荐答案

这是设计使然.

[class.compare.default] (强调我的意思)

[class.compare.default] (emphasis mine)

3 如果类定义未明确声明== 运算符函数,但声明默认的三向比较 运算符函数,==运算符函数被隐式声明 具有与三向比较运算符功能相同的访问权限. X类的隐式声明的==运算符是内联的 成员,并且在X的定义中定义为默认值.

3 If the class definition does not explicitly declare an == operator function, but declares a defaulted three-way comparison operator function, an == operator function is declared implicitly with the same access as the three-way comparison operator function. The implicitly-declared == operator for a class X is an inline member 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 cannot use a defaulted <=>. In addition, 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 non-sensible default, the language leaves it up to the programmer.

这篇关于没有为C ++ 20中的自定义太空飞船运算符实现定义等式运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆