Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to manually declare >= and <= operators?

If I already have operator > and operator < defined (and operator ==), do I need to define operator >= and operator <=, or will the compiler declare them for me if I intentionally don't declare them?

Also, if I have operator == defined, will the compiler declare operator != for me?

like image 416
Jamin Grey Avatar asked Jul 23 '13 17:07

Jamin Grey


2 Answers

No, the Compiler won't declare/define any of the operators you did not define manually. However, Boost.Operators might be to your liking - it does exactly what you want the compiler to do.

like image 110
Arne Mertz Avatar answered Nov 11 '22 22:11

Arne Mertz


The compiler won't do anything itself for you here, but it's relatively simple to generate automatically by inheriting from an appropriate class, something like:

template< typename DerivedType >
class ComparisonOperators
{
public:

    friend bool         operator!=( 
                            DerivedType const&  lhs,
                            DerivedType const&  rhs )
    {
        return !(lhs  == rhs);
    }

    friend bool         operator<=( 
                            DerivedType const&  lhs,
                            DerivedType const&  rhs )
    {
        return !(rhs < lhs);
    }

    friend bool         operator>( 
                            DerivedType const&  lhs,
                            DerivedType const&  rhs )
    {
        return rhs < lhs;
    }

    friend bool         operator>=( 
                            DerivedType const&  lhs,
                            DerivedType const&  rhs )
    {
        return !(lhs < rhs);
    }

protected:
                        ~ComparisonOperators() {}
} ;

Define < and == in your class, and derive from this, and you'll get all of the operators:

class MyClass : public ComparisonOperators<MyClass>
{
    //  ...
public:
    bool operator==( MyClass const& other ) const;
    bool operator<( MyClass const& other ) const;
    //  ...
};

Just a note: I've manually simplified the version I actual use, which defines == and < as well, looks for the member functions compare and isEqual, and uses compare for == and != when there is no isEqual. I don't think I've introduced any errors, but you never know.

like image 32
James Kanze Avatar answered Nov 11 '22 22:11

James Kanze