Comparison Functor Types vs. operator<

前端 未结 7 2072
庸人自扰
庸人自扰 2021-01-02 04:54

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

7条回答
  •  离开以前
    2021-01-02 05:15

    I probably wouldn't go as far as the Google style guide.

    I think that what they are getting at is that when you overload operator< and operator==, you are making a decision for every use of the type, while the functor types only apply to that collection.

    If the only thing you need the comparators for is to put the item in a collection, then it's better to have a function specifically for that context rather than the operators that would apply in all contexts.

    You may want to sort purchase orders chronologically, but in general, it would make sense to compare them by their total price. If we overload operator< to compare dates so that we can load them into a collection, we are introducing the risk that another client may misuse our operator< which they may think compares the total prices.

提交回复
热议问题