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

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

Also, if I have operator == set , the compiler will declare operator! = ?

+6
source share
3 answers

No, the compiler will not declare / define any of the statements that you did not define manually. However, Boost.Operators can, at its discretion - it does exactly what you want the compiler to do.

+6
source

The compiler will not do anything for you here, but it is relatively simple to create it automatically, inheriting from the corresponding 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 extract from this, and you will get all the operators:

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

Just a note: I manually simplified the version used, which defines == and < , and also looks for a member of the compare and isEqual , and uses compare for == and != When there is no isEqual . I don’t think I made any mistakes, but you never know.

+5
source

There are already good answers here using boost and inheritance. But, as someone remarked, using inheritance to create an operator seems ... wrong.

I know that #define are taboo in C ++, but still this is what I use here.

I have a #define in my general utility that looks something like this:

 #define CREATE_COMPARITORS(name) \ inline bool operator>(const name &o){return o<*this;} \ inline bool operator<=(const name &o){return not (o<*this);} \ inline bool operator>=(const name &o){return not (*this<o);} \ inline bool operator!=(const name &o){return not (*this==o);} 

Then, if I have a class, all I need to declare is operator< and operator== :

 class ttt{ //... bool operator<(const ttt &o); bool operator==(const ttt &o); CREATE_COMPARITORS(ttt); //... }; 
0
source

Source: https://habr.com/ru/post/950112/


All Articles