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

前端 未结 5 506
猫巷女王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:03

    The typical reason is that when you do this:

    bool less_than(const Point&, const Point&);
    // ...
    std::sort(..., &less_than);
    

    The template argument for the predicate is the following:

    bool(const Point&,const Point&)
    

    Since the sort function receives a function pointer, it is more difficult for the compiler to inline the predicate use inside std::sort(). This happens because you could have another function

    bool greater_than(const Point&, const Point&);
    

    which has the exact same type, meaning the std::sort() instatiation would be shared between the two predicates. (remember that I said that it makes inlining more difficult, not impossible).

    In contrast, when you do this:

    struct less_than {
        bool operator()(const Point&, const Point&) const;
    };
    // ...
    std::sort(..., less_than());
    
    
    struct greater_than {
        bool operator()(const Point&, const Point&) const;
    };
    // ...
    std::sort(..., greater_than());
    

    The compiler generates a unique template instantiation for std::sort() for each predicate, making it easier to inline the predicate's definition.

提交回复
热议问题