All the basic comparisons (<
, <=
, ==
, !=
, >=
, >
) have an associated function object (std::less
, std::less_equal
, std::equal_to
, std::not_equal_to
, std::greater_equal
, std::greater
).
Does the spaceship operator <=>
have a similar function object?
If not, why was it not added to the standard library?
The three-way comparison operator “<=>” is called a spaceship operator. The spaceship operator determines for two objects A and B whether A < B, A = B, or A > B. The spaceship operator or the compiler can auto-generate it for us.
Spaceship Operator 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.
The std::less is a is a member of the functional class (<functional. h>) used for performing comparisons.
std::greater::operator()Checks whether lhs is greater than rhs .
Some very smart people on the standardization committee noticed that the spaceship operator will always perform a lexicographic comparison of elements no matter what. Unconditionally performing lexicographic comparisons can lead to inefficient generated code with the equality operator in particular. The canonical example is comparing two strings.
The spaceship operator is a welcomed addition to C++ and it is one of the features that will simplify and help you to write less code, and, sometimes, less is more. So buckle up with C++20’s spaceship operator!
The new addition of the spaceship operator has considerably changed how the comparison is viewed. It has affected how comaprison semantics work at the language level.
We urge you to go out and try the spaceship operator, it’s available right now in Visual Studio 2019 under /std:c++latest! As a note, the changes introduced through P1185R2 will be available in Visual Studio 2019 version 16.2.
std::compare_three_way
is the function object for three-way comparison (aka. spaceship operator).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With