gpt4 book ai didi

c++ - boost operator totally_ordered 由 less_than_comparable 和 equality_comparable 组成

转载 作者:行者123 更新时间:2023-11-30 05:18:44 25 4
gpt4 key购买 nike

作为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))可能导致性能不佳

¹ https://www.sgi.com/tech/stl/StrictWeakOrdering.html

关于c++ - boost operator totally_ordered 由 less_than_comparable 和 equality_comparable 组成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41498326/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com