增压操作员totally_ordered由less_than_comparable和equality_comparabl
boost operator totally_ordered composed of less_than_comparable and equality_comparable
正如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
相关文章:
- D-lang being faster than C++?
- MATLAB faster than LAPACK?
- "How to use long long data-type rather than pointers data-type to modify other variables ?"
- 如何实现随机访问迭代器的"less than operator"?
- 如何在 C++ 类中重载 'less than' 运算符以比较常量?
- 为什么我收到错误:"there is more than one default constructor"?
- std::tuple faster than std::array?
- 有没有办法通过'greater/lesser than'而不是"="来定义'int'?
- "compares less than 0"是什么意思?
- OpenSSL 错误"data greater than mod len"
- 特征:如何将"greater than"的结果(在ArrayXf上)转换为特征向量
- Is calloc better than malloc?
- "less than" 与GCC 4与6的ifstream比较
- 在 C 族中,在一个循环中,为什么"less than or equal to"比"less than"符号更受欢迎?
- Is ++(a = b); faster than a = b + 1;?
- VS 编译器错误 C2752 ( "more than one partial specialization matches" ) 在 STL 中
- Is while faster than for?
- 我怎样才能写得"if not greater than or equal to some value"雄辩?
- OpenGL ES Matrix/Vector-Transform different than on desktiop
- Is int faster than long?