In STL algorithms, function pointers and function-like passing algorithms can be used.
So why do we still need regular function adapters?
Because regular function adapters do not have the "matching capability"
Example:
/** File: Main. CPP * Author: Vicky. H * mail: eclipser@163.com */# include <iostream> # include <vector> # include <algorithm> # include <functional> Class A {public: int ID; () {} A (int id): ID (ID) {}}; // common function. Two parameters are required! However, for STL algorithms such as for_each and find_if, only one parameter is provided. For 2nd parameters, STD: bind2nd provides bool id_eq (const A * a, const Int & ID) {return a-> id = ID;}/***/INT main (void) {A * AA [] = {New A (1 ), new A (2), new A (3), new A (4), new A (5)}; STD: vector <A *> AV (AA, AA + 5); const int id = 5; // We Need to query a // STD: find_if (Av. begin (), Av. end (), id_eq); // note that we cannot pass 2nd parameters for id_eq as 5. the following error occurs: Too few arguments to function, this also requires a common function adapter for the reason // STD: ptr_fun (id_eq); // STD: bind2nd (STD: ptr_fun (id_eq), ID); STD :: vector <A * >:: iterator it = STD: find_if (Av. begin (), Av. end (), STD: bind2nd (STD: ptr_fun (id_eq), ID); STD: cout <(* It)-> id <STD :: endl; // destroy pointer... for (INT I = 0; I <Av. size (); I ++) delete AV [I]; return 0 ;}
5
Member function adapter:
/** File: Main. CPP * Author: Vicky. H * Email: eclipser@163.com */# include <iostream> # include <algorithm> # include <functional> # include <vector> Class A {public: Virtual void display () = 0 ;}; Class B: Public A {public: Virtual void display () {STD: cout <"B" <STD: Endl ;}virtual ~ B () {}}; Class C: Public A {public: void display () {STD: cout <"C" <STD: Endl ;}}; class D: Public B {public: void display () {STD: cout <"D" <STD: Endl ;}}; /***/INT main (void) {STD: vector <A *> pav; Pav. push_back (New B); Pav. push_back (New C); Pav. push_back (new D); Pav. push_back (New B); For (INT I = 0; I <Pav. size (); I ++) {pav [I]-> display ();} STD: cout <"---------------------------" <STD :: Endl;/** why cannot I directly pass the function name like a global function? The member function must be in the & Class Name: function name format, because the static member function must be considered! */STD: for_each (Pav. begin (), Pav. end (), STD: mem_fun (& A: Display)/* STD: mem_fun_ref (& A: Display) because of the pointer we created, here the member function adapter for processing objects cannot be used */); Return 0 ;}
B
C
D
B
---------------------------
B
C
D
B