stl functor (function object)

Define (stl-source analysis):

In fact, that is functor objects on a "behavior similar function".


That subject is the object, just use like a function.


Transfer function pointer:

template<typename T>
bool compare_to(const T& x, const T &y) { return x > y;}

template<typename T>
void print_compare(T fun) {
    std::cout << fun(3, 5) << std::endl;
}

int main() {
    print_compare(compare_to<int>);
    return 0;
}
Passing a function pointer


Imitation transfer function:

template<typename T>
struct CompareTo : public std::binary_function<T, T, bool> {
    bool operator() (const T& x, const T &y) const { return x > y;}
 public:
    CompareTo() {}
};

template<typename T>
void print_compare(T fun) {
    std::cout << fun(3, 5) << std::endl;
}

int main() {
    print_compare(CompareTo<int>());
    return 0;
}
This can be seen like CompareTo incoming calls as a function.

Actually not the case, that the above function pointer passing logic is not the same,

Function pointer: Incoming address of the function, and therefore is a direct function calls

Functor: actually passed a temporary variable CompareTo temporary created, Compare <int> () constructor is called, so the object is passed

Print_compare call back call is actually calling the operator CompareTo () function, and therefore the behavior of functor incoming object look more like function calls


Published 140 original articles · won praise 28 · views 180 000 +

Guess you like

Origin blog.csdn.net/qq_16097611/article/details/78879637