Encapsulate a function pointer into a function object
The function object is STL.Algorithm. If you can encapsulate existing function pointers, functions, and member functions into function objects, you can obtain STL algorithm support and reduce the workload of writing function objects. The basic idea is to construct a function object, which can call function pointers internally.
Bool Foo (int x) {return x> = 2;} typedef bool (* foo_pointer) (int x); Template <typename pointer_type, typename arg_type, typename return_type> class pointer_bind {public: explicit pointer_bind (pointer_type P): P _ (p) {} return_type operator () (arg_type PARAM) {return (* P _) (PARAM);} PRIVATE: pointer_type P _;}; int main (INT argc, char ** argv) {foo_pointer P = Foo; cout <(* p) (3) <Endl; pointer_bind <foo_pointer, Int, bool> binder (p); cout <binder (4) <Endl; vector <int> V; V. push_back (1); V. push_back (2); vector <int >:: iterator itor = STD: find_if (v. begin (), V. end (), binder); cout <* itor <Endl; return 0 ;}
The above pointer_bind is very elementary, but it is ready to work. I can use it to construct a function object and directly call or pass it to the find_if function as the query condition.
Boost: bind to encapsulate function pointers
This article introduces the main character. Boost provides a series of BIND functions that can encapsulate function pointers, member functions, function objects, virtual functions, and function references in a temporary function object. It supports up to 9 parameters and intelligently analyzes the return type.
Int main (INT argc, char ** argv) {foo_pointer P = Foo; vector <int> V; V. push_back (1); V. push_back (2); vector <int >:: iterator itor = STD: find_if (v. begin (), V. end (), boost: BIND (p, _ 1); cout <* itor <Endl; return 0 ;}
Boost: BIND (p, _ 1) is a strange and simple method. _ 1 refers to the first int x parameter. You do not need to inform the parameter type and return type. Boost: BIND can be automatically inferred. Boost: There are many bind contents, which will be analyzed later.