How do I get operators >
, >=
, <=
, and !=
from ==
and <
?
standard header <utility>
defines a namespace std::rel_ops that defines the above operators in terms of operators ==
and <
, but I don't know how to use it (coax my code into using such definitions for:
std::sort(v.begin(), v.end(), std::greater<MyType>);
where I have defined non-member operators:
bool operator < (const MyType & lhs, const MyType & rhs);
bool operator == (const MyType & lhs, const MyType & rhs);
If I #include <utility>
and specify using namespace std::rel_ops;
the compiler still complains that binary '>' : no operator found which takes a left-hand operand of type 'MyType'
..
I'd use the <boost/operators.hpp>
header :
#include <boost/operators.hpp>
struct S : private boost::totally_ordered<S>
{
bool operator<(const S&) const { return false; }
bool operator==(const S&) const { return true; }
};
int main () {
S s;
s < s;
s > s;
s <= s;
s >= s;
s == s;
s != s;
}
Or, if you prefer non-member operators:
#include <boost/operators.hpp>
struct S : private boost::totally_ordered<S>
{
};
bool operator<(const S&, const S&) { return false; }
bool operator==(const S&, const S&) { return true; }
int main () {
S s;
s < s;
s > s;
s <= s;
s >= s;
s == s;
s != s;
}
Actually only <
should suffice. Do it like so:
a == b
<=> !(a<b) && !(b<a)
a > b
<=> b < a
a <= b
<=> !(b<a)
a != b
<=> (a<b) || (b < a)
And so on for symmetric cases.
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