如何获取运算符 >
, >=
, <=
, 和 !=
来自 ==
和 <
?
标准标题 <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;
}
或者,如果您更喜欢非成员(member)运营商:
#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;
}