Transfer: https: //blog.csdn.net/shuilan0066/article/details/82788954
Example 1: Common Functions
void gFunc()
{
cout << "gFunc" << endl;
}
int main ()
{
std::function<void()> f = gFunc;
f();
getchar();
return 0;
}
示例2 模板函数 template <class T> T g_Add(T i, T j) { cout << i + j; return i + j; } int main() { std::function<int(int,int)> f = g_Add<int>; f(2,3); getchar(); return 0; }
Example Three: anonymous function Auto g_Lambda = [] ( int I, int J) { return I + J; }; // anonymous functions here semicolon int main () { STD :: function < int ( int , int ) > F = g_Lambda; COUT << F ( 2 , . 3 ); getchar (); return 0 ; }
Example Four: Object function / function object struct the Add { int operator () ( int I, int J) { return I + J; } }; // template function object Template < class T> struct ADDT { T operator () (T I, T J) { return I + J; } }; int main () { STD :: function < int ( int , int )> = F the Add (); COUT<<f(2,3)<<endl; std::function<int(int, int)> ft = AddT<int>(); cout << ft(5, 6)<<endl; getchar(); return 0; }
Example 5: class member function class Computer { public : static int the Add ( int I, int J) { return I + J; } Template < class T> static T ADDT (T I, T J) { return I + J; } int ADDN ( int I, int J) { return I + J; } }; // storing member function calls int main () { // . 1, class static function :: function STD < int ( int , int )> = F & Computer :: the Add; COUT << F ( . 1 , . 1 ) << endl; // 2, class static template function STD :: function < int ( int , int )>. ft :: = & Computer ADDT < int > ; COUT <<. ft ( . 1 , . 1 ) << endl; // common function to bind to the class object need to construct Computer C; // . 3, need to use common functions bind, to address & c class object bindings on STD :: function < int ( int , int)> = FN STD :: the bind (Computer & ADDN ::, & C, placeholders. 1 :: _, _ :: placeholders 2); COUT << fN ( . 1 , . 1 ) << endl; // . 4, normal function, may be such calls personally feel that the ratio bind trouble, do not recommend std :: function < int ( const Computer &, int , int )> = FN2 & Computer :: ADDn; cout << FN2 (c, 1 , 1 ) << endl; getchar (); return 0 ; }