Comparison Functor Types vs. operator<

前端 未结 7 2074
庸人自扰
庸人自扰 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:26

    Generally, defining operator< is better and simpler.

    The case where you would want to use functors is when you need multiple ways of comparing a particular type. For example:

    class Person;
    
    struct CompareByHeight {
        bool operator()(const Person &a, const Person &b);
    };
    
    struct CompareByWeight {
        bool operator()(const Person &a, const Person &b);
    };
    

    In this case there may not be a good "default" way to compare and order people so not defining operator< and using functors may be better. You could also say that generally people are ordered by height, and so operator< just calls CompareByHeight, and anyone who needs Person's to be ordered by weight has to use CompareByWeight explicitly.

    Often times the problem is that defining the functors is left up to the user of the class, so that you tend to get many redefinitions of the same thing, whenever the class needs to be used in an ordered container.

提交回复
热议问题