如何从==
和<
获取运算符>
、>=
、<=
和!=
标准标头<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'
..
发布于 2013-02-07 17:04:17
我会使用头:
#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;
}
发布于 2013-02-07 16:54:43
实际上,只有<
应该足够了。如下所示:
a == b
<=> !(a<b) && !(b<a)
a > b
<=> b < a
a <= b
<=> !(b<a)
a != b
<=> (a<b) || (b < a)
对于对称情况,依此类推。
发布于 2013-02-07 16:56:21
> equals !(<=)
>= equals !(<)
<= equals == or <
!= equals !(==)
像这样的东西?
https://stackoverflow.com/questions/14756512
复制