4.bind綁定
阿新 • • 發佈:2018-03-26
new esp gpo strlen 成員函數 class oid work func
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 1213 //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 3536 //類中有綁定函數 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 }
4.bind綁定