开发者

What is the minimum set of operators I need to overload?

开发者 https://www.devze.com 2023-02-02 21:35 出处:网络
which operators of the comparison (<=, >, ==, etc.) do You usually implement as your basic operators, which You can after use to implement the rest comparison operators or to make all possible comp

which operators of the comparison (<=, >, ==, etc.) do You usually implement as your basic operators, which You can after use to implement the rest comparison operators or to make all possible compariso开发者_如何学编程ns among the classes?


You can implement all six of the operators in terms of == and < using the following equivalencies:

a != b    =>    !(a == b)
a > b     =>    b < a
a >= b    =>    !(a < b)
a <= b    =>    !(b < a)


I normally implement operator== for objects and also operator!=. Many objects do not have a collating sequence, so the comparison operators <, <=, >, >= do not make sense.

Also, by using boost::equality_comparable and boost::less_than_comparable only operator== and operator< need to be implemented. These can be found in boost/operators.hpp.

Also, I have learned that placing comparison operators in base clases or interface classes can become quite tricky as they allow Descendent_A to be compared to Descendent_B, which are two different descendent classes.

Comparison operators should be implemented as needed in classes. Many classes do not need them. Also, beware of implementing them or defining them in base classes without considering the ramifications of inheritance.


For classes where they are applicable I usually implement operator< and operator== "natively" because of their prominence in standard algorithms and containers.

I then implement the other four in terms of these.

Another approach that I sometimes consider is implementing a "compare" function that returns 1, 0, or -1 in the style of strcmp and the implement all the other operators in terms of this. I only do this if operator< and operator== look like they need to share much of the same code which seems to happen less often that I think.

0

精彩评论

暂无评论...
验证码 换一张
取 消