参见英文答案 >
Idiomatic use of std::rel_ops4个
如何获取运算符>,> =,< =和!= from ==和<? 标准标题< utility>定义了一个命名空间std :: rel_ops,它根据operator ==和<来定义上述运算符,但我不知道如何使用它(使我的代码使用这些定义:
如何获取运算符>,> =,< =和!= from ==和<? 标准标题< utility>定义了一个命名空间std :: rel_ops,它根据operator ==和<来定义上述运算符,但我不知道如何使用它(使我的代码使用这些定义:
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>并使用namespace std :: rel_ops指定;编译器仍然抱怨二进制’>’ :找不到哪个运算符带有’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;
}