When are stateless class functors useful in place of a c style function?

前端 未结 5 463
猫巷女王i
猫巷女王i 2021-01-05 08:38

I\'ve found some good examples of functors on SO like this one, and all the convincing examples seem to use state in the class that defines operator().

5条回答
  •  醉梦人生
    2021-01-05 09:26

    Another reason is that sometimes one comparison function is not enough. Let's say we have a vector of pointers:

    struct X { string name; };
    vector> v;
    

    Now if we want to sort the vector by name, we have to define our own predicate for the sort function:

    struct Cmp1
    {
        bool operator()(const shared_ptr& left, const shared_ptr& right) const
        { return left->name < right->name; }
    };
    

    That's cool, but what do we do when we need to find the objects with specific name? To work with equal_range, the predicate needs to have two different comparison functions:

    struct Cmp2
    {
        bool operator()(const shared_ptr& left, const string& right) const
        { return left->name < right; }
    
        bool operator()(const string& left, const shared_ptr& right) const
        { return left < right->name; }
    };
    

    This allows us to call equal_range with a string name object:

    equal_range(v.begin(), v.end(), name, Cmp2())
    

提交回复
热议问题