Can't use default inequality operator inside structure member function

74 views Asked by At

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?

1

There are 1 answers

3
Nicol Bolas On BEST ANSWER

C++20 does not define operator != for you. What it does is that, when you use the != operator, if no matching operator != function exists (it's more complex than that, but nevermind that now), it can rewrite your code to call operator == and negate the result. And operator == is a real function generated by defaulting operator <=>.

However, you are not using the != operator. You are asking to call the function named operator !=. There is no such function, hence the error.

If you want to get the rewriting behavior, you need to use the actual != operator.