繁体   English   中英

由less_than_comparable 和equality_comparable 组成的boost 运算符totally_ordered

[英]boost operator totally_ordered composed of less_than_comparable and equality_comparable

正如boost operator 文档所说,模板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; }
};

在这里, Points 将按x排序,根据您建议的实现,具有相等x点将是等效的

然而,由于y可能不同,显然这些点不能保证相等

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

  • 希望用户非常意识到这种影响
  • 意识到使用(!(lhs < rhs) && !(rhs < lhs))可能会导致性能欠佳

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM