首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >由less_than_comparable和equality_comparable组成的boost算子less_than_comparable

由less_than_comparable和equality_comparable组成的boost算子less_than_comparable
EN

Stack Overflow用户
提问于 2017-01-06 03:12:51
回答 1查看 1.5K关注 0票数 1

正如boost操作符文档所说,模板totally_ordered由模板less_than_comparable和tempalte equality_comparable组成。

这意味着如果一个类是从模板totally_ordered中继承的,那么在使用operator==或操作符!=时,必须实现operator==。

在我看来,如果实现了operator<,operator==可以自动生成,如(!(lhs < rhs)和!(lhs

代码块:

代码语言:javascript
复制
#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;
}
EN

回答 1

Stack Overflow用户

发布于 2017-01-06 14:20:50

严格的弱排序可以将等价物归为等价物,例如:

代码语言:javascript
复制
struct Point { 
     int x,y; 
     bool operator<(Point const& other) const { return x < other.x; }
};

在这里,点将由x排序,而具有相同x的点将根据建议的实现等效。

但是,由于y可能是不同的,因此显然不能保证各点相等。

只有当比较实际上是一个全序时,我们才能使用相对比较运算符来生成相等运算。我只能怀疑图书馆的作者

  • 希望用户非常清楚这一影响。
  • 意识到使用(!(lhs < rhs) && !(rhs < lhs))可能会导致次优性能

1-1- https://www.sgi.com/tech/stl/StrictWeakOrdering.html

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41498326

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档