Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the <=> ("spaceship", three-way comparison) operator in C++?

While I was trying to learn about C++ operators, I stumbled upon a strange comparison operator on cppreference.com,* in a table that looked like this:

enter image description here

"Well, if these are common operators in C++, I better learn them", I thought. But all my attempts to elucidate this mystery were unsuccessful. Even here, on Stack Overflow I had no luck in my search.

Is there a connection between <=> and C++?

And if there is, what does this operator do exactly?

* In the meantime cppreference.com updated that page and now contains information about the<=>operator.

like image 305
q-l-p Avatar asked Nov 24 '17 04:11

q-l-p


People also ask

What is the === comparison operator used for?

Equal to ( === ) — returns true if the value on the left is equal to the value on the right, otherwise it returns false .

What is the spaceship operator?

In PHP 7, a new feature, spaceship operator has been introduced. It is used to compare two expressions. It returns -1, 0 or 1 when first expression is respectively less than, equal to, or greater than second expression.

What does <=> mean in C++?

@hkBattousai it means that the object returns, when compared < 0 evaluates to true. That is, if a < b then (a <=> b) < 0 is always true.


1 Answers

This is called the three-way comparison operator.

According to the P0515 paper proposal:

There’s a new three-way comparison operator, <=>. The expression a <=> b returns an object that compares <0 if a < b, compares >0 if a > b, and compares ==0 if a and b are equal/equivalent.

To write all comparisons for your type, just write operator<=> that returns the appropriate category type:

  • Return an _ordering if your type naturally supports <, and we’ll efficiently generate <, >, <=, >=, ==, and !=; otherwise return an _equality, and we’ll efficiently generate == and !=.

  • Return strong if for your type a == b implies f(a) == f(b) (substitutability, where f reads only comparison-salient state accessible using the nonprivate const interface), otherwise return weak.

The cppreference says:

The three-way comparison operator expressions have the form

lhs <=> rhs   (1)   

The expression returns an object that

  • compares <0 if lhs < rhs
  • compares >0 if lhs > rhs
  • and compares ==0 if lhs and rhs are equal/equivalent.
like image 88
msc Avatar answered Sep 30 '22 19:09

msc