Search code examples
c++equalityjson-spiritcustom-operator

custom == operator, does it matter which side?


JSON Spirit has a convenient operator==

template< class Config >
bool Value_impl< Config >::operator==( const Value_impl& lhs ) const
{
    if( this == &lhs ) return true;

    if( type() != lhs.type() ) return false;

    return v_ == lhs.v_; 
}

The variable lhs looks like the familiar "left hand side" from many other examples, implying to me that this will not work as expected if for what this operator is assigned is not on the left hand side.

Is that correct? If so, why?

In either case, please quote the standard.


Solution

  • b = x == y; translates to b = x.operator==( y ); so an operator==() must be defined for x which takes an argument of whatever type y is.

    class Y
    {
        public:
    
    };
    
    class X
    {
        public:
    
        bool operator==( Y rhs )
        {
            return false;
        }
    };
    
    void tester()
    {
    
        X x;
        Y y;
    
        bool b = x == y; // works
        b = y == x;      // error
    
    }