Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use std::rel_ops to supply comparison operators automatically? [duplicate]

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'..

like image 674
Mordachai Avatar asked Feb 07 '13 16:02

Mordachai


2 Answers

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;
}
like image 176
Robᵩ Avatar answered Sep 27 '22 23:09

Robᵩ


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.

like image 44
Ivaylo Strandjev Avatar answered Sep 27 '22 21:09

Ivaylo Strandjev