0

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.

  • 1
    When in a member function the parameter is the right hand side, not left. – Rapptz May 19 '14 at 21:01
  • 6
    The side in this case doesn't matter but if you had `operator==(int);` member function then you can't expect `4 == my_class` to work but `my_class == 4` would. – Rapptz May 19 '14 at 21:07
  • 1
    `::operator==( const Value_impl& lhs )` **`lhs` is a `rhs`**, and if you turn yourself (or your code) upside down ... The naming is chosen wrong here IMHO! – πάντα ῥεῖ May 19 '14 at 21:11
  • 1
    @Rapptz it's worth noting, that `T::operator==(int)` has simply nothing to do with `4 == obj`, so your statement 'you can't expect `4 == obj` to work' is unfounded. Of course such 'comparision' **can work**, for example if the class `T` has a cast operator defined which allows conversion to some integral type value, or if there is external `operator==(int, T&)` function defined. – CiaPan May 19 '14 at 22:05
  • 1
    @CiaPan: That's pretty much exactly what he said. I think you misread. – Mooing Duck May 19 '14 at 22:19

1 Answers1

1

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

}
Rob K
  • 8,757
  • 2
  • 32
  • 36
  • 1
    See chapter 11 of The C++ Programming Language, Special Edition. Note also that I did not mention non-member operator overloading above. That works slightly differently, and is generally preferable to overloading as a member function. – Rob K May 20 '14 at 12:59