Comparison Functor Types vs. operator<

2019-02-09 02:25发布

In the Google C++ Style Guide, the section on Operator Overloading recommends against overloading any operators ("except in rare, special circumstances"). Specifically, it recommends:

In particular, do not overload operator== or operator< just so that your class can be used as a key in an STL container; instead, you should create equality and comparison functor types when declaring the container.

I'm a little fuzzy on what such a functor would look like, but my main question is, why would you want to write your own functors for this? Wouldn't defining operator<, and using the standard std::less<T> function, be simpler? Is there any advantage to using one over the other?

7条回答
冷血范
2楼-- · 2019-02-09 03:17

Except for the more fundamental types, the less-than operation isn't always trivial, and even equality may vary from situation to situation.

Imagine the situation of an airline that wants to assign all passengers a boarding number. This number reflects the boarding order (of course). Now, what determines who comes before who? You might just take the order in which the customers registered – in that case, the less-than operation would compare the check-in times. You might also consider the price customers paid for their tickets – less-than would now compare ticket prices.

… and so on. All in all, it's just not meaningful to define an operator < on the Passenger class although it may be required to have passengers in a sorted container. I think that's what Google warns against.

查看更多
登录 后发表回答