Home >Backend Development >C++ >Why Can't I Use `==` and `!=` with a Custom `<=>` Operator in C 20?
` Operator in C 20? " />
Non-defaulted Operator <=> and the Absence of == and !=
In C 20, the spaceship operator <=> provides a general-purpose comparison mechanism. However, a strange behavior arises when using a custom three-way comparison implementation.
Default Implementation Generates == and !=
Consider the following code using the default implementation of <=>:
struct X { int Dummy = 0; auto operator<=>(const X&) const = default; // Default implementation };
In this case, the code compiles successfully and allows the use of == and != for comparing instances of X:
X a, b; a == b; // OK!
Custom Implementation Blocks == and !=
However, when a custom implementation of <=> is provided:
struct X { int Dummy = 0; auto operator<=>(const X& other) const { return Dummy <=> other.Dummy; } };
Compiling results in the error:
error C2676: binary '==': 'X' does not define this operator or a conversion to a type acceptable to the predefined operator
Reason for Behavior
This behavior is intentional. According to the C 20 standard:
If the class definition does not explicitly declare an == operator function, but declares a defaulted three-way comparison function, an == operator function is declared implicitly with the same access as the three-way comparison operator function.
Only a defaulted <=> operator generates a synthesized ==. This is because classes like std::vector should not use a non-defaulted <=> for equality tests, as it may be less efficient than a custom implementation.
Therefore, if a class has a custom <=> implementation, the programmer must also provide a custom == implementation to ensure correct comparison behavior.
The above is the detailed content of Why Can't I Use `==` and `!=` with a Custom `<=>` Operator in C 20?. For more information, please follow other related articles on the PHP Chinese website!