Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't use default inequality operator inside structure member function

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Question: Why this is happening and is there way to not define inequality operator and use it inside member function?

>Solution :

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 <=>.

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading