C++11之function和bind
2016-02-24 20:48
405 查看
首先看看function的使用方法
#include <iostream> #include <functional> using namespace std; // 一般的函数 void Func() { cout << __FUNCTION__ << endl; } class Test { public: // 类的静态函数 static void TestFunc(int a) { cout << __FUNCTION__ << endl; cout << a << endl; } }; // 仿函数 class Foo { public: void operator()(int a) { cout << __FUNCTION__ << endl; cout << a << endl; } }; int main(int arc,char** argv) { Foo foo; // 定义两个function对象 function<void()> fun1 = Func; function<void(int)> fun2 = Test::TestFunc; function<void(int)> fun3 = foo; // 像使用普通函数一样使用function对象 fun1(); fun2(10); fun3(20); return 0; }bind的使用方式
#include <iostream> #include <functional> using namespace std; // 一般的函数 void Func() { cout << __FUNCTION__ << endl; } class Test { public: // 类的静态函数 static void TestFunc(int a) { cout << __FUNCTION__ << endl; cout << a << endl; } }; // 仿函数 class Foo { public: void operator()(int a,int b) { cout << __FUNCTION__ << endl; cout << "a = "<< a << " b= " << b << endl; } void Output(int a) { cout << __FUNCTION__ << endl; cout << a << endl; } }; int main(int arc,char** argv) { Foo foo; // bind的使用 auto fun1 = bind(Func); auto fun2 = bind(Test::TestFunc, std::placeholders::_1); // std::placeholders::_1,std::placeholders::_2等是占位符,表示这个位置在函数被调用时,被传入的第1,2个参数所代替 auto fun3 = bind(foo, 10,std::placeholders::_1); auto fun4 = bind(&Foo::Output, &foo, std::placeholders::_1); fun1(); fun2(20); // 输出20 fun3(30); // 输出 10,30 fun4(40); // 输出 40 return 0; }