作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
作为boost operator document比如,模板totally_ordered由模板less_than_comparable和模板equality_comparable组成。
这意味着如果一个类继承自模板 totally_ordered,则在使用 operator== 或 operator!= 时必须实现 operator==。
在我看来,如果实现了 operator<,operator== 可以像 (!(lhs < rhs) && !(rhs < lhs)) 一样自动生成。那么,operator== 是必要的吗?
代码片段:
#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;
}
最佳答案
严格的弱排序可能会将不相等的元素评为等价的¹例如:
struct Point {
int x,y;
bool operator<(Point const& other) const { return x < other.x; }
};
在这里,积分将按 x
排序, 和等于 x
的点根据您建议的实现,将等效。
但是,由于 y
可能不同,显然不能保证这些点相等。
只有当比较实际上是全序时,我们才能使用相对比较运算符生成相等运算。我只能怀疑图书馆的作者
(!(lhs < rhs) && !(rhs < lhs))
可能导致性能不佳关于c++ - boost operator totally_ordered 由 less_than_comparable 和 equality_comparable 组成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41498326/
作为boost operator document比如,模板totally_ordered由模板less_than_comparable和模板equality_comparable组成。 这意味着如果
我是一名优秀的程序员,十分优秀!