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?
c++ c++20 comparison-operators spaceship-operator
operator<=>
(or evendefault
ing 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 knowingif( 1.1 < 2.2 )
, then it probably doesn't make much sense to use<=>
– Ted Lyngmo 2 days ago<=>
and==
. Less chance of having a mistake/bug than writing 6 comparison operators. – Eljay 2 days ago<=>
to perform a comparison, or about using<=>
in any general context? – Drew Dormann 2 days ago