#include <boost/function.hpp>

为atoi取别名fun,fun实质上是函数指针

 1 #include <iostream>
 2 #include <boost/function.hpp>
 3 
 4 void main()
 5 {
 6     boost::function<int(char *)>fun = atoi;//为atoi取别名fun,fun实质上是函数指针
 7 
 8     std::cout << fun("123") + fun("234") << std::endl;
 9 
10     fun = strlen;
11 
12     std::cout << fun("123") + fun("234") << std::endl;
13 }

结合boost::bind使用

 1 #include <iostream>
 2 #include <boost/bind.hpp>
 3 #include <boost/function.hpp>
 4 
 5 void main()
 6 {
 7     boost::function<int(char *)>fun;
 8 
 9     fun = boost::bind(strcmp, "ABC", _1);//绑定strcmp,判断和"ABC"是否相同
10 
11     std::cout << fun("123") << std::endl;
12 
13     std::cout << fun("ABC") << std::endl;
14 }

function和bind配合使用可以很方便的实现类成员回调,极好的应用于一些需要回调的场合。

 1 #include <iostream>
 2 #include <boost/bind.hpp>
 3 #include <boost/function.hpp>
 4 
 5 class manager
 6 {
 7 public:
 8     void allstart()
 9     {
10         for (int i = 0; i < 10; i++)
11         {
12             if (workid)
13             {
14                 workid(i);
15             }
16         }
17     }
18     void setcallback(boost::function<void(int)>newid)//绑定调用
19     {
20         workid = newid;
21     }
22 public:
23     boost::function<void(int)> workid;
24 };
25 
26 class worker
27 {
28 public:
29     void run(int toid)
30     {
31         id = toid;
32         std::cout << id << "工作" << std::endl;
33     }
34 public:
35     int id;
36 };
37 
38 void main()
39 {
40     manager m;
41     worker w;
42 
43     m.setcallback(boost::bind(&worker::run, &w, _1));//绑定
44     //类的成员函数需要对象来调用,绑定了一个默认的对象
45 
46     m.allstart();
47 }

ref库

当在某些情况下需要拷贝对象参数时,如果该对象无法进行拷贝,或者拷贝代价过高,这时候就可以选择ref

 1 #include <iostream>
 2 #include <vector>
 3 #include <algorithm>
 4 #include <boost/bind.hpp>
 5 #include <boost/function.hpp>
 6 
 7 void print(std::ostream &os, int i)
 8 {
 9     os << i << std::endl;
10 }
11 
12 void main()
13 {
14     boost::function<void(int)>pt = boost::bind(print, boost::ref(std::cout), _1);//std::cout不能拷贝,所以用ref
15 
16     std::vector<int>v;
17     v.push_back(11);
18     v.push_back(12);
19     v.push_back(13);
20 
21     for_each(v.begin(), v.end(), pt);
22 }
原文地址:https://www.cnblogs.com/denggelin/p/5767999.html