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

Mor*_*hai 6 c++ templates c++11 visual-studio-2012

我如何获得运营商>,>=,<=,并!===<

标准头<utility>定义了一个命名空间的std :: rel_ops定义在运营商方面的上述运营商==<,但我不知道如何使用它(哄我的代码到使用这样的定义为:

std::sort(v.begin(), v.end(), std::greater<MyType>); 
Run Code Online (Sandbox Code Playgroud)

我在哪里定义了非成员运营商:

bool operator < (const MyType & lhs, const MyType & rhs);
bool operator == (const MyType & lhs, const MyType & rhs);
Run Code Online (Sandbox Code Playgroud)

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

Rob*_*obᵩ 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;
}
Run Code Online (Sandbox Code Playgroud)

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

#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;
}
Run Code Online (Sandbox Code Playgroud)

  • 注意:您可以使用boost :: totally_ordered <S>而不是多重继承.此外,我倾向于使用私有继承来做这种事情.最后,我知道这是一个简单的例子,但是operator ==()通常应该为无状态类型返回true. (3认同)