相关疑难解决方法(0)

当“operator <=>”就足够了时,为什么我必须提供“operator ==”?

#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

52
推荐指数
4
解决办法
5074
查看次数

没有为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 …

c++ spaceship-operator c++20

42
推荐指数
3
解决办法
2365
查看次数