增压操作员totally_ordered由less_than_comparable和equality_comparabl

boost operator totally_ordered composed of less_than_comparable and equality_comparable

本文关键字:comparable than comparabl equality less 操作员 totally ordered      更新时间:2023-10-16

正如boost运算符文档所说,模板totally_ordered由模板less_than_comparable和临时equality_comparable组成。

这意味着,如果一个类是模板totally_ordered固有的,则在使用运算符==或运算符!=时必须实现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;
}

严格的弱排序可能会将不相等元素视为等价¹例如:

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