how to use std::rel_ops to supply comparison opera

2019-02-17 05:45发布

This question already has an answer here:

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

3条回答
乱世女痞
2楼-- · 2019-02-17 06:20

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;
}
查看更多
叼着烟拽天下
3楼-- · 2019-02-17 06:21

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.

查看更多
啃猪蹄的小仙女
4楼-- · 2019-02-17 06:23

> equals !(<=)
>= equals !(<)
<= equals == or <
!= equals !(==)

Something like this?

查看更多
登录 后发表回答