相关疑难解决方法(0)

没有为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
查看次数

为什么默认的三向运算符 (spaceship &lt;=&gt;) 生成相等运算符 (==) 而用户定义的三向运算符不生成?

考虑这个代码:

#include <iostream>
#include <compare>

class A {
public:
  int i = {};

  std::strong_ordering operator<=> (A const& r) const
  {
    return i <=> r.i;
  }
};

void TestA()
{
    A a;
    A b;

    std::cout<< (a<b);    
    std::cout<< (a>b);
    std::cout<< (a<=b);
    std::cout<< (a>=b);
    //std::cout<< (a==b); //ERROR
    std::cout << 'E';
    //std::cout<< (a!=b); //ERROR
    std::cout << 'E';
    std::cout<< std::is_eq(a<=>b);
    std::cout<< std::is_neq(a<=>b) << std::endl;
}

class B {
public:
  int i = {};

  std::strong_ordering operator<=> (B const& r) const = default;

};


void TestB()
{ …
Run Code Online (Sandbox Code Playgroud)

c++ operator-overloading spaceship-operator c++20

2
推荐指数
1
解决办法
209
查看次数