Why should I use the three-way comparison operator (<=>) instead of the two-way comparison operators? Does this have an advantage?

5
#include <compare>
#include <iostream>

int main()
{ 
   auto comp1 = 1.1 <=> 2.2;
   auto comp2 = -1 <=> 1;
   std::cout << typeid(comp1).name()<<"\n"<<typeid(comp2).name();
}

Output:

struct std::partial_ordering
struct std::strong_ordering

I know that if the operands have an integral type, the operator returns a prvalue of type std::strong_ordering. I also know if the operands have a floating-point type, the operator yields a prvalue of type std::partial_ordering.

But why should I use a three-way comparison operator instead of two-way operators (==, !=, <, <=, >, >=)? Is there an advantage this gives me?

Share
Improve this question
5
  • 3
    Here's something that you can read open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0515r2.pdf by the big man himself. – anastaciu 2 days ago
  • 3
    It depends on the context I would say. If you're creating a class, implementing operator<=> (or even defaulting if possible) saves time (development and maintenance) instead of having to implement all of them manually. If you on the other hand are interested in knowing if( 1.1 < 2.2 ), then it probably doesn't make much sense to use <=> – Ted Lyngmo 2 days ago
  • 1
    Less code to write using 2 comparison operators <=> and ==. Less chance of having a mistake/bug than writing 6 comparison operators. – Eljay 2 days ago
  • 1
    Are you asking about using <=> to perform a comparison, or about using <=> in any general context? – Drew Dormann 2 days ago
  • @DrewDormann Actually both – east1000 2 days ago

Comments

Popular posts from this blog

Meaning of `{}` for return expression

Get current scroll position of ScrollView in React Native

flutter websocket connection issue