如何使用std :: rel_ops自动提供比较运算符?

时间:2013-02-07 16:52:20

标签: c++ templates c++11 visual-studio-2012

如何从>>=获取运营商<=!===<

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

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

3 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:1)

实际上只有<就足够了。这样做:

a == b&lt; =&gt; !(a<b) && !(b<a)

a > b&lt; =&gt; b < a

a <= b&lt; =&gt; !(b<a)

a != b&lt; =&gt; (a<b) || (b < a)

等对称案例。

答案 2 :(得分:0)


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

这样的东西?