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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With