6

如何从and 获取运算符>, >=, <=, and ?!===<

标准标头定义了一个命名空间 std::rel_ops ,它根据运算符and<utility>定义上述运算符,但我不知道如何使用它(哄我的代码使用这样的定义:==<

std::sort(v.begin(), v.end(), std::greater<MyType>); 

我在其中定义了非成员运算符:

bool operator < (const MyType & lhs, const MyType & rhs);
bool operator == (const MyType & lhs, const MyType & rhs);

如果我#include <utility>并指定using namespace std::rel_ops;编译器仍然抱怨binary '>' : no operator found which takes a left-hand operand of type 'MyType'..

4

3 回答 3

8

我会使用<boost/operators.hpp>标题:

#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;
}

或者,如果您更喜欢非会员运营商:

#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;
}
于 2013-02-07T17:04:17.027 回答
1

其实只要<够了。这样做:

a == b<=>!(a<b) && !(b<a)

a > b <=>b < a

a <= b<=>!(b<a)

a != b<=>(a<b) || (b < a)

对于对称情况,依此类推。

于 2013-02-07T16:54:42.947 回答
0

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

像这样的东西?

于 2013-02-07T16:56:21.320 回答