4.bind绑定
1 #include <iostream> 2 #include <string> 3 #include <boost/bind.hpp> 4 #include <boost/function.hpp> 5 #include <vector> 6 #include <algorithm> 7 #include <functional> 8 #include <stdlib.h> 9 using namespace std; 10 using namespace boost; 11 12 13 //function函数包装器 14 void mainC() 15 { 16 //atoi //char * to int 17 boost::function<int(char *)> fun = atoi; 18 cout << fun("123") + fun("234") << endl; 19 fun = strlen; 20 cout << fun("123") + fun("234") << endl; 21 cin.get(); 22 } 23 24 //函数包装器指定某个参数 25 void mainD() 26 { 27 boost::function<int(char *)> fun = atoi; 28 cout << fun("123") + fun("234") << endl; 29 fun = boost::bind(strcmp, "ABC", _1); 30 cout << fun("123") << endl; 31 cout << fun("ABC") << endl; 32 cin.get(); 33 } 34 35 36 //类中有绑定函数 37 class manager 38 { 39 public: 40 //调用绑定的函数 41 void allstart() 42 { 43 for (int i = 0; i < 15; i++) 44 { 45 if (workid) 46 { 47 workid(i); 48 } 49 } 50 } 51 52 //绑定调用 53 void setcallback(boost::function<void(int)> newid) 54 { 55 workid = newid; 56 } 57 58 public: 59 //绑定一个函数 60 boost::function<void(int)> workid; 61 }; 62 63 //worker类 64 class worker 65 { 66 public: 67 void run(int toid) 68 { 69 id = toid; 70 cout << id << "工作" << endl; 71 } 72 public: 73 int id; 74 }; 75 76 77 void main() 78 { 79 manager m; 80 worker w; 81 82 //类的成员函数需要对象来调用 83 //给manager类的成员函数绑定了一个默认的函数,以及对象 84 m.setcallback(boost::bind(&worker::run, &w, _1)); 85 //调用 86 m.allstart(); 87 cin.get(); 88 }