【问题标题】:how to use std::rel_ops to supply comparison operators automatically? [duplicate]如何使用 std::rel_ops 自动提供比较运算符? [复制]
【发布时间】:2013-01-23 06:30:19
【问题描述】:

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

标准头<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 &lt;utility&gt; 并指定 using namespace std::rel_ops;,编译器仍然会抱怨 binary '&gt;' : no operator found which takes a left-hand operand of type 'MyType'..

【问题讨论】:

  • “编译器,请使用 std::rel_ops for MyType”怎么说?
  • 我不知道。也许有一些using declarations 所以它被 ADL 拾取...自己写这些更容易,或者如果你很懒,你可以利用Boost.Operators
  • 嗯,这个编辑大大改变了问题。
  • 也许问题是我缺少的是 ADL。因为我的运营商是非会员..

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


【解决方案1】:

我会使用 &lt;boost/operators.hpp&gt; 标头:

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

【讨论】:

  • 注意:你可以只使用 boost::totally_ordered 而不是多重继承。另外,我倾向于对这种事情使用私有继承。最后,我知道这是一个简单的例子,但是对于无状态类型,operator==() 通常应该返回 true。
  • 所有优秀的建议。谢谢,@Nevin。
  • 注意:我刚刚检查了它是否可以与非成员运算符一起正常工作(如果可能,我更喜欢)。
  • 谢谢@gx_ - 我已经更新了我的答案。
【解决方案2】:

实际上只有&lt; 就足够了。这样做:

a == b !(a&lt;b) &amp;&amp; !(b&lt;a)

a &gt; b b &lt; a

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

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

对称情况下以此类推。

【讨论】:

  • 啊 - 你的答案更好。担心你不能使用!,但你做到了:)
  • 我自己知道如何做到这一点——而且它们每个都很简单。我只是有一种模糊的感觉,有一种方法可以要求标准库根据我已经提供的两个定义来提供这些定义。需要为定义operator ==operator &lt; 的每个T 编写上述内容似乎很愚蠢,不是吗?
  • &lt; 还不够。您实现的 == 实际测试的是 equivalence,而不是 equality
【解决方案3】:

> equals !(&lt=)
>= equals !(&lt)
&lt= equals == or &lt
!= equals !(==)

这样的?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多