1 int add(int a, int b)
2 {
3 cout << a + b << endl;
4 return a + b;
5 }
6
7 //常规包装器
8 void main1()
9 {
10 vector<int> myint = { 1,2,3,4,5 };
11 //绑定操作
12 //for_each(myint.begin(), myint.end(), bind(add, 10, _1));
13
14 //绑定lambda表达式,借助函数包装器
15 boost::function<void(int,int)> fun = [](int a, int b)
16 {
17 cout << a + b << endl;
18 };
19 for_each(myint.begin(), myint.end(), bind(fun,10,_1));
20 cin.get();
21 }
22
23 //继承异构二元操作类
24 class addit :public std::binary_function<int, int, void>
25 {
26 public:
27 void operator()(int i, int j)
28 {
29 cout << i + j << endl;
30 }
31 };
32
33 //绑定仿函数
34 void main2()
35 {
36 vector<int> myint = { 1,2,3,4,5 };
37 //绑定仿函数
38 for_each(myint.begin(), myint.end(), bind(addit(), 10, _1));
39 cin.get();
40 }
41
42 void main3()
43 {
44 //myv可以是四种类型之一的任何一种类型
45 typedef boost::variant<int, double, char, const char *> myv;
46 std::vector<myv> s_values;
47 s_values.push_back(10);
48 s_values.push_back('X');
49 s_values.push_back(10.9);
50 s_values.push_back("hello");
51 s_values.push_back('z');
52 //根据数据类型来获取
53 char ch = boost::get<char>(s_values.back());
54 double db = boost::get<double>(s_values.at(2));
55 cout << db << endl;
56
57 cin.get();
58 }
59
60 //manager管理worker 类与类之间通信
61 class manager
62 {
63 public:
64 //函数指针
65 boost::function<void(int)> workid;
66 void setcallback(boost::function<void(int)> newworkid)
67 {
68 workid = newworkid;
69 }
70
71 void allgo()
72 {
73 for (int i = 0; i < 10; i++)
74 {
75 if (workid)
76 {
77 workid(i);
78 }
79 }
80 }
81 };
82
83 class worker
84 {
85 public:
86 int id;
87 void run(int toid)
88 {
89 id = toid;
90 cout << id << "干活" << endl;
91 }
92 };
93
94 void main6()
95 {
96 manager m;
97 worker w;
98 //传递一个绑定的函数,调用者是w,需要一个参数
99 m.setcallback(boost::bind(&worker::run, &w, _1));
100 m.allgo();
101 cin.get();
102 }
1 //function
2 void main5()
3 {
4 boost::function<int(char *)>fun = atoi;
5 cout << fun("123") + fun("34") << endl;
6
7 fun = strlen;
8 cout << fun("234") << endl;
9 cin.get();
10 }