Consider slightly modified example from cppreferenece.com using default comparisons:
struct Point
{
int x;
int y;
auto operator<=>(const Point&) const = default;
//bool operator!=(const Point&) const = default;
bool isDifferent(const Point& another) const
{
// Fails without explicit operator !=
return operator != (another);
}
bool isSame(const Point& another) const
{
// Always OK
return operator == (another);
}
};
int main()
{
Point pt1{1, 1}, pt2{1, 2};
std::cout << std::boolalpha
<< (pt1 == pt2) << ' ' // Always OK
<< (pt1 != pt2) << ' ' // Always OK
<< (pt1 < pt2) << ' '
<< (pt1 <= pt2) << ' '
<< (pt1 > pt2) << ' '
<< (pt1 >= pt2) << ' ';
}
https://godbolt.org/z/dq56T3ssG
Here function that uses equality operator compiles fine. Other function that uses inequality operator fails with "operator not defined" error. However if inequality operator used outside of member function everything works fine.
Question: Why this is happening and is there way to not define inequality operator and use it inside member function?
C++20 does not define
operator !=
for you. What it does is that, when you use the!=
operator, if no matchingoperator !=
function exists (it's more complex than that, but nevermind that now), it can rewrite your code to calloperator ==
and negate the result. Andoperator ==
is a real function generated by defaultingoperator <=>
.However, you are not using the
!=
operator. You are asking to call the function namedoperator !=
. There is no such function, hence the error.If you want to get the rewriting behavior, you need to use the actual
!=
operator.