本文介绍了如何使用std :: rel_ops自动提供比较运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取运算符> > = != / code>?

How do I get operators >, >=, <=, and != from == and <?

标题< utility> 定义了一个命名空间std :: rel_ops上面的运算符在运算符 == < ,但我不知道如何使用它cox我的代码使用这样的定义为:

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);

如果I #include < utility> 并指定使用命名空间std :: rel_ops; ,编译器仍然会抱怨 binary'没有操作符发现,它接受类型'MyType'的左手操作数 ..

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

推荐答案

I请使用标题:

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

这篇关于如何使用std :: rel_ops自动提供比较运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 05:09