0

I don't understand why this code doesn't compile. According to some websites, a == b should be rewritten as a.operator<=>(b) == 0, however both clang and gcc fail to compile.

#include <utility>
#include <stdio.h>

struct A {
public:
    int x_ = 0;

public:
    std::strong_ordering operator<=>(const A& o) const 
    {
        return int(x_ == o.x_ ? 0 : x_ < o.x_ ? -1 : 1) <=> 0;
    }
};

int main()
{
  A a{1};
  A b{2};

  if(a == b) printf("a==b\n");
}

However, if you use the default, everything works!

...
   std::strong_ordering operator<=>(const A& o) const = default;
...

So my question is, how do you write the default implementation of <=> by hand?

Barry
  • 286,269
  • 29
  • 621
  • 977
Zendel
  • 485
  • 3
  • 14
  • 3
    First, the hand-written one should be just `return x_ <=> o.x_;` Second, if you write a custom `<=>`, you have to also write a custom `==`. A defaulted `<=>` also generates a defaulted `==`. – Barry Jan 06 '21 at 16:54
  • 1
    " According to some websites [...]" Those websites are incorrect. `a == b` does not rewrite to `(a <=> b) == 0`. – Barry Jan 06 '21 at 16:55
  • 1
    *"According to some websites..."* Those website were using the early draft of the C++20 spaceship operator proposal. The C++20 standard separated out the `==` behavior, because a custom `<=>` could be inefficient for `==` and `!=` predicates. – Eljay Jan 06 '21 at 17:08

0 Answers0