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

how to use std::rel_ops to supply comparison operators automatically?

本文关键字:比较 运算符 何使用 std relops      更新时间:2023-10-16

如何从==<中获取运算符>>=<=!=

标准头<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'。。

我会使用<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;
}

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

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

a > b<=>b < a

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

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

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


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

像这样的东西?