正如boost操作符文档所说,模板totally_ordered由模板less_than_comparable和tempalte equality_comparable组成。
这意味着如果一个类是从模板totally_ordered中继承的,那么在使用operator==或操作符!=时,必须实现operator==。
在我看来,如果实现了operator<,operator==可以自动生成,如(!(lhs < rhs)和!(lhs
代码块:
#include <boost/operators.hpp>
class Foo : public boost::totally_ordered<Foo>
{
public:
explicit Foo(const int num) : m_nMem(num){}
friend bool operator< (const Foo& lhs, const Foo& rhs)
{
return lhs.m_nMem < rhs.m_nMem;
}
// Is operator== necessary ?
// Is operator== equal to (!(lhs < rhs) && !(rhs < lhs)) ?
//friend bool operator== (const Foo& lhs, const Foo& rhs)
//{
// return lhs.m_nMem == rhs.m_nMem;
//}
private:
int m_nMem;
};
int main()
{
Foo foo_1(1), foo_2(2);
foo_1 == foo_2; // compiler error , no operator==
return 0;
}发布于 2017-01-06 14:20:50
严格的弱排序可以将等价物归为等价物,例如:
struct Point {
int x,y;
bool operator<(Point const& other) const { return x < other.x; }
};在这里,点将由x排序,而具有相同x的点将根据建议的实现等效。
但是,由于y可能是不同的,因此显然不能保证各点相等。
只有当比较实际上是一个全序时,我们才能使用相对比较运算符来生成相等运算。我只能怀疑图书馆的作者
(!(lhs < rhs) && !(rhs < lhs))可能会导致次优性能https://stackoverflow.com/questions/41498326
复制相似问题