详细解析boost中bind的实现

转载地址:http://blog.csdn.net/hengyunabc/article/details/7773250

写在前面的话

在C++11之后,std::bind是C++标准库的一个组件了。一开始想弄个C++11的实现来研究下,发现里面用到了可变参数模板(代码变得非常神奇).

http://llvm.org/svn/llvm-project/libcxx/trunk/include/functional

还是弄个原始点的boost的实现来研究下。


话说网上关于boost::bind的实现的文章也有不少,不过大多数都是贴一段代码,再扯一通,结果到头来什么都没看明白。(起码LZ是。。)

花了一天的功夫,最终从boost::bind的源代码中抠出了可编绎运行的代码。

下面一步一步来解析boost::bind的实现。

标准库中的fouctor和bind1st的实现

首先从简单的入手。先看下标准库中的fouctor和bind1st的实现(为了防止和标准库的命名冲突,全部都在命名后面加了2)。

  1. #include <iostream>  
  2. #include <algorithm>  
  3. using namespace std;  
  4. template<typename _Arg1, typename _Arg2, typename _Result>  
  5. struct binary_function2 {  
  6.     typedef _Arg1 first_argument_type;  
  7.     typedef _Arg2 second_argument_type;  
  8.     typedef _Result result_type;  
  9. };  
  10.   
  11. template<typename _Tp>  
  12. struct equal_to2: public binary_function2<_Tp, _Tp, bool> {  
  13.     bool operator()(const _Tp& __x, const _Tp& __y) const {  
  14.         return __x == __y;  
  15.     }  
  16. };  
  17.   
  18. template<typename _Arg, typename _Result>  
  19. struct unary_function2 {  
  20.     typedef _Arg argument_type;  
  21.     typedef _Result result_type;  
  22. };  
  23.   
  24. template<typename _Operation>  
  25. class binder1st2: public unary_function2<  
  26.         typename _Operation::second_argument_type,  
  27.         typename _Operation::result_type> {  
  28. protected:  
  29.     _Operation op;  
  30.     typename _Operation::first_argument_type value;  
  31.   
  32. public:  
  33.     binder1st2(const _Operation& __x,  
  34.             const typename _Operation::first_argument_type& __y) :  
  35.             op(__x), value(__y) {  
  36.     }  
  37.   
  38.     typename _Operation::result_type operator()(  
  39.             const typename _Operation::second_argument_type& __x) const {  
  40.         return op(value, __x);  
  41.     }  
  42.   
  43.     typename _Operation::result_type operator()(  
  44.             typename _Operation::second_argument_type& __x) const {  
  45.         return op(value, __x);  
  46.     }  
  47. };  
  48.   
  49. template<typename _Operation, typename _Tp>  
  50. inline binder1st2<_Operation> bind1st2(const _Operation& __fn, const _Tp& __x) {  
  51.     typedef typename _Operation::first_argument_type _Arg1_type;  
  52.     return binder1st2<_Operation>(__fn, _Arg1_type(__x));  
  53. }  
  54.   
  55. int main() {  
  56.     binder1st2<equal_to2<int> > equal_to_10(equal_to2<int>(), 10);  
  57.     int numbers[] = { 10, 20, 30, 40, 50, 10 };  
  58.     int cx;  
  59.     cx = std::count_if(numbers, numbers + 6, bind1st(equal_to2<int>(), 10));  
  60.     cout << "There are " << cx << " elements that are equal to 10.\n";  
  61. }  

上面的实现还是比较简单的,希望还没有看晕。:)

从代码可以看出binder1st的实现,实制上是把参数保存起来,等到调用时,再取出来使用。

boost::bind从原理上来说,也是这么回事,但是要复杂得多。

解析简化版bind2

下面是从boost::bind源码中抠出来的,一个简单的bind的实现(bind改为bind2),主流编译器应该都可以编统执行。

为了方便理解程序运行过程,代码中增加了一些cout输出。

myBind.h:

  1. #ifndef BOOST_BIND_BIND_HPP_INCLUDED__Mybind  
  2. #define BOOST_BIND_BIND_HPP_INCLUDED__Mybind  
  3.   
  4. #include <iostream>  
  5. using namespace std;  
  6. namespace boost {  
  7. template<class T> struct is_placeholder {  
  8.     enum _vt {  
  9.         value = 0  
  10.     };  
  11. };  
  12. template<int I> struct arg {  
  13.     arg() {  
  14.     }  
  15. };  
  16. template<class T>  
  17. struct type {  
  18. };  
  19. namespace _bi // implementation details  
  20. {  
  21.   
  22. template<class A1> struct storage1 {  
  23.     explicit storage1(A1 a1) :  
  24.             a1_(a1) {  
  25.         cout<<"storage1  storage1(A1 a1)"<<endl;  
  26.     }  
  27.     A1 a1_;  
  28. };  
  29. template<int I> struct storage1<boost::arg<I> > {  
  30.     explicit storage1(boost::arg<I>) {  
  31.         cout<<"storage1  storage1(boost::arg<I>)"<<endl;  
  32.     }  
  33.     static boost::arg<I> a1_() {  
  34.         return boost::arg<I>();  
  35.     }  
  36. };  
  37. template<int I> struct storage1<boost::arg<I> (*)()> {  
  38.     explicit storage1(boost::arg<I> (*)()) {  
  39.         cout<<"storage1  storage1(boost::arg<I> (*)())"<<endl;  
  40.     }  
  41.     static boost::arg<I> a1_() {  
  42.         return boost::arg<I>();  
  43.     }  
  44. };  
  45. // 2  
  46. template<class A1, class A2> struct storage2: public storage1<A1> {  
  47.     typedef storage1<A1> inherited;  
  48.     storage2(A1 a1, A2 a2) :  
  49.             storage1<A1>(a1), a2_(a2) {  
  50.         cout<<"storage2  storage2(A1 a1, A2 a2)"<<endl;  
  51.     }  
  52.     A2 a2_;  
  53. };  
  54. template<class A1, int I> struct storage2<A1, boost::arg<I> > : public storage1<  
  55.         A1> {  
  56.     typedef storage1<A1> inherited;  
  57.     storage2(A1 a1, boost::arg<I>) :  
  58.             storage1<A1>(a1) {  
  59.         cout<<"storage2  storage2(A1 a1, boost::arg<I>)"<<endl;  
  60.     }  
  61.     static boost::arg<I> a2_() {  
  62.         return boost::arg<I>();  
  63.     }  
  64. };  
  65. template<class A1, int I> struct storage2<A1, boost::arg<I> (*)()> : public storage1<  
  66.         A1> {  
  67.     typedef storage1<A1> inherited;  
  68.     storage2(A1 a1, boost::arg<I> (*)()) :  
  69.             storage1<A1>(a1) {  
  70.         cout<<"storage2  storage2(A1 a1, boost::arg<I> (*)())"<<endl;  
  71.     }  
  72.     static boost::arg<I> a2_() {  
  73.         return boost::arg<I>();  
  74.     }  
  75. };  
  76. // result_traits  
  77. template<class R, class F> struct result_traits {  
  78.     typedef R type;  
  79. };  
  80. struct unspecified {  
  81. };  
  82. template<class F> struct result_traits<unspecified, F> {  
  83.     typedef typename F::result_type type;  
  84. };  
  85. // value  
  86. template<class T> class value {  
  87. public:  
  88.     value(T const & t) :  
  89.             t_(t) {  
  90.     }  
  91.     T & get() {  
  92.         return t_;  
  93.     }  
  94. private:  
  95.     T t_;  
  96. };  
  97. // type  
  98. template<class T> class type {  
  99. };  
  100. // unwrap  
  101. template<class F> struct unwrapper {  
  102.     static inline F & unwrap(F & f, long) {  
  103.         return f;  
  104.     }  
  105. };  
  106. // listN  
  107. class list0 {  
  108. public:  
  109.     list0() {  
  110.     }  
  111.     template<class T> T & operator[](_bi::value<T> & v) const {  
  112.         cout << "list0  T & operator[](_bi::value<T> & v)" << endl;  
  113.         return v.get();  
  114.     }  
  115.     template<class R, class F, class A> R operator()(type<R>, F & f, A &,  
  116.             long) {  
  117.         cout << "list0  R operator()(type<R>, F & f, A &, long)" << endl;  
  118.         return unwrapper<F>::unwrap(f, 0)();  
  119.     }  
  120.     template<class F, class A> void operator()(type<void>, F & f, A &, int) {  
  121.         cout << "list0  void operator()(type<void>, F & f, A &, int)" << endl;  
  122.         unwrapper<F>::unwrap(f, 0)();  
  123.     }  
  124. };  
  125.   
  126. template<class A1> class list1: private storage1<A1> {  
  127. private:  
  128.     typedef storage1<A1> base_type;  
  129. public:  
  130.     explicit list1(A1 a1) :  
  131.             base_type(a1) {  
  132.     }  
  133.     A1 operator[](boost::arg<1>) const {  
  134.         return base_type::a1_;  
  135.     }  
  136.     A1 operator[](boost::arg<1> (*)()) const {  
  137.         return base_type::a1_;  
  138.     }  
  139.     template<class T> T & operator[](_bi::value<T> & v) const {  
  140.         return v.get();  
  141.     }  
  142.     template<class R, class F, class A> R operator()(type<R>, F & f, A & a,  
  143.             long) {  
  144.         return unwrapper<F>::unwrap(f, 0)(a[base_type::a1_]);  
  145.     }  
  146. //  template<class F, class A> void operator()(type<void>, F & f, A & a, int) {  
  147. //      unwrapper<F>::unwrap(f, 0)(a[base_type::a1_]);  
  148. //  }  
  149. };  
  150.   
  151. template<class A1, class A2> class list2: private storage2<A1, A2> {  
  152. private:  
  153.     typedef storage2<A1, A2> base_type;  
  154. public:  
  155.     list2(A1 a1, A2 a2) :  
  156.             base_type(a1, a2) {  
  157.     }  
  158.     A1 operator[](boost::arg<1>) const {  
  159.         cout << "list2  A1 operator[](boost::arg<1>)" << endl;  
  160.         return base_type::a1_;  
  161.     }  
  162.     A2 operator[](boost::arg<2>) const {  
  163.         cout << "list2  A1 operator[](boost::arg<2>)" << endl;  
  164.         return base_type::a2_;  
  165.     }  
  166.     A1 operator[](boost::arg<1> (*)()) const {  
  167.         cout << "list2  A1 operator[](boost::arg<1> (*)())" << endl;  
  168.         return base_type::a1_;  
  169.     }  
  170.     A2 operator[](boost::arg<2> (*)()) const {  
  171.         cout << "list2  A1 operator[](boost::arg<2> (*)())" << endl;  
  172.         return base_type::a2_;  
  173.     }  
  174.     template<class T> T & operator[](_bi::value<T> & v) const {  
  175.         cout << "T & operator[](_bi::value<T> & v)" << endl;  
  176.         return v.get();  
  177.     }  
  178.     template<class R, class F, class A> R operator()(type<R>, F & f, A & a,  
  179.             long) {  
  180.         return f(a[base_type::a1_], a[base_type::a2_]);  
  181. //      return unwrapper<F>::unwrap(f, 0)(a[base_type::a1_], a[base_type::a2_]);  
  182.     }  
  183. //  template<class F, class A> void operator()(type<void>, F & f, A & a, int) {  
  184. //      unwrapper<F>::unwrap(f, 0)(a[base_type::a1_], a[base_type::a2_]);  
  185. //  }  
  186. };  
  187. // bind_t  
  188. template<class R, class F, class L> class bind_t {  
  189. public:  
  190.     typedef bind_t this_type;  
  191.     bind_t(F f, L const & l) :  
  192.             f_(f), l_(l) {  
  193.     }  
  194.     typedef typename result_traits<R, F>::type result_type;  
  195.     result_type operator()() {  
  196.         cout << "bind_t::result_type operator()()" << endl;  
  197.         list0 a;  
  198.         return l_(type<result_type>(), f_, a, 0);  
  199.     }  
  200.     template<class A1> result_type operator()(A1 & a1) {  
  201.         list1<A1 &> a(a1);  
  202.         return l_(type<result_type>(), f_, a, 0);  
  203.     }  
  204.     template<class A1, class A2> result_type operator()(A1 & a1, A2 & a2) {  
  205.         list2<A1 &, A2 &> a(a1, a2);  
  206.         return l_(type<result_type>(), f_, a, 0);  
  207.     }  
  208. private:  
  209.     F f_;  
  210.     L l_;  
  211. };  
  212.   
  213. template<class T, int I> struct add_value_2 {  
  214.     typedef boost::arg<I> type;  
  215. };  
  216.   
  217. template<class T> struct add_value_2<T, 0> {  
  218.     typedef _bi::value<T> type;  
  219. };  
  220. template<class T> struct add_value {  
  221.     typedef typename add_value_2<T, boost::is_placeholder<T>::value>::type type;  
  222. };  
  223. template<class T> struct add_value<value<T> > {  
  224.     typedef _bi::value<T> type;  
  225. };  
  226. template<int I> struct add_value<arg<I> > {  
  227.     typedef boost::arg<I> type;  
  228. };  
  229. //template<int I> struct add_value<arg<I> (*)()> {  
  230. //  typedef boost::arg<I> (*type)();  
  231. //};  
  232. template<class R, class F, class L> struct add_value<bind_t<R, F, L> > {  
  233.     typedef bind_t<R, F, L> type;  
  234. };  
  235. // list_av_N  
  236. template<class A1> struct list_av_1 {  
  237.     typedef typename add_value<A1>::type B1;  
  238.     typedef list1<B1> type;  
  239. };  
  240. template<class A1, class A2> struct list_av_2 {  
  241.     typedef typename add_value<A1>::type B1;  
  242.     typedef typename add_value<A2>::type B2;  
  243.     typedef list2<B1, B2> type;  
  244. };  
  245. // namespace _bi  
  246.   
  247. // function pointers  
  248. template<class R>  
  249. _bi::bind_t<R, R (*)(), _bi::list0> bind2(R (*f)()) {  
  250.     typedef R (*F)();  
  251.     typedef _bi::list0 list_type;  
  252.     return _bi::bind_t<R, F, list_type>(f, list_type());  
  253. }  
  254. template<class R, class B1, class A1>  
  255. _bi::bind_t<R, R (*)(B1), typename _bi::list_av_1<A1>::type> bind2(R (*f)(B1),  
  256.         A1 a1) {  
  257.     typedef R (*F)(B1);  
  258.     typedef typename _bi::list_av_1<A1>::type list_type;  
  259.     return _bi::bind_t<R, F, list_type>(f, list_type(a1));  
  260. }  
  261. template<class R, class B1, class B2, class A1, class A2>  
  262. _bi::bind_t<R, R (*)(B1, B2), typename _bi::list_av_2<A1, A2>::type> bind2(  
  263.         R (*f)(B1, B2), A1 a1, A2 a2) {  
  264.     typedef R (*F)(B1, B2);  
  265.     typedef typename _bi::list_av_2<A1, A2>::type list_type;  
  266.     return _bi::bind_t<R, F, list_type>(f, list_type(a1, a2));  
  267. }  
  268. // namespace boost  
  269.   
  270. namespace {  
  271. boost::arg<1> _1;  
  272. boost::arg<2> _2;  
  273. }  
  274. #endif // #ifndef BOOST_BIND_BIND_HPP_INCLUDED__Mybind  

main.cpp:
  1. #include <iostream>  
  2. #include "myBind.h"  
  3. using namespace std;  
  4. void tow_arguments(int i1, int i2) {  
  5.     std::cout << i1 << i2 << '\n';  
  6. }  
  7.   
  8. class Test{  
  9. };  
  10. void testClass(Test t, int i){  
  11.     cout<<"testClass,Test,int"<<endl;  
  12. }  
  13.   
  14. int main() {  
  15.     int i1 = 1, i2 = 2;  
  16.   
  17.     (boost::bind2(&tow_arguments, 123, _1))(i1, i2);  
  18.     (boost::bind2(&tow_arguments, _1, _2))(i1, i2);  
  19.     (boost::bind2(&tow_arguments, _2, _1))(i1, i2);  
  20.     (boost::bind2(&tow_arguments, _1, _1))(i1, i2);  
  21.   
  22.     (boost::bind2(&tow_arguments, 222, 666))(i1, i2);  
  23.   
  24.     Test t;  
  25.     (boost::bind2(&testClass, _1, 666))(t, i2);  
  26.     (boost::bind2(&testClass, _1, 666))(t);  
  27.     (boost::bind2(&testClass, t, 666))();  
  28. }  

在上面的代码中有很多个类,有几个是比较重要的any,storage,list和bind_t。

先来看类any:

  1. template<int I> struct arg {  
  2.     arg() {  
  3.     }  
  4. };  
  5. namespace {  
  6. boost::arg<1> _1;  
  7. boost::arg<2> _2;  
  8. }  
在上面的代码中,我们看到了_1和_2,没错,所谓的占位符就是这么个东东,在匿名名字空间中定义的空的struct。

接下来是storage1,storage2类:

  1. template<class A1> struct storage1 {  
  2.     explicit storage1(A1 a1) :  
  3.             a1_(a1) {  
  4.     }  
  5.   
  6.     A1 a1_;  
  7. };  
  8. ...  
  9. // 2  
  10. template<class A1, class A2> struct storage2: public storage1<A1> {  
  11.     typedef storage1<A1> inherited;  
  12.   
  13.     storage2(A1 a1, A2 a2) :  
  14.             storage1<A1>(a1), a2_(a2) {  
  15.     }  
  16.   
  17.     A2 a2_;  
  18. };  
  19. ...  

可以看出storage类只是简单的继承关系, 实际上storage类是用来存储bind函数所传递进来的参数的值的,之所以采用继承而不用组合,其实有精妙的用处。

接着看类list1和list2,它俩分别是storage1和storage2的子类(即参数是存放在listN类中的)

  1. template<class A1> class list1: private storage1<A1> {  
  2. ...  
  3. }  
  4. template<class A1, class A2> class list2: private storage2<A1, A2> {  
  5. ...  
  6. }  
仔细看代码,可以看到 list1和list2重载了operator [ ] 和operator () 函数,这些重载函数很关键,下面会谈到。

再看类bind_t:

  1. template<class R, class F, class L> class bind_t {  
  2. public:  
  3.     typedef bind_t this_type;  
  4.     bind_t(F f, L const & l) :  
  5.             f_(f), l_(l) {  
  6.     }  
  7.     typedef typename result_traits<R, F>::type result_type;  
  8.   
  9.     result_type operator()() {  
  10.         cout<<"bind_t::result_type operator()()"<<endl;  
  11.         list0 a;  
  12.         return l_(type<result_type>(), f_, a, 0);  
  13.     }  
  14. ...  
  15. private:  
  16.     F f_;   <strong>//bind所绑定的函数</strong>  
  17.     L l_;  <strong> //实际是是listN类,存放bind传绑定的参数</strong>  
  18. };  
同样,我们可以看到bind_t类重载了operator ()函数,实际上,bind_t类是bind函数的返回类型,bind_t实际上是一个stl意义上的funtor。

注意bind_t的两个成员F f_ 和 L l_,这里是关键之处。


介绍完关键类,下面以main.cpp中下面部分代码为例,详细说明它的工作流程。

  1. int i1 = 1, i2 = 2;  
  2. (boost::bind2(&tow_arguments, 123, _1))(i1, i2);  
首先bind2函数返回一个bind_t类,这个类中的F成员,保存了tow_arguments函数指针,L成员(即list2类),保存了参数123 和 _1。

bind_t类采用的是以下的特化:

  1. template<class R, class B1, class B2, class A1, class A2>  
  2. _bi::bind_t<R, R (*)(B1, B2), typename _bi::list_av_2<A1, A2>::type> bind2(  
  3.         R (*f)(B1, B2), A1 a1, A2 a2)  

其中storage2类(list2的父类)和storage1类,分别采用的是以下的特化:

  1. template<class A1, int I> struct storage2<A1, boost::arg<I> > : public storage1<A1>  
  1. template<class A1> struct storage1  
(这里可以试下把123和_1互换位置,就能发现storage系列类用继承的精妙之处了,这里不展开了)

当bind_t调用operator (i1, i2)函数时,即以下函数:

  1. template<class A1, class A2> result_type operator()(A1 & a1, A2 & a2) {  
  2.     list2<A1 &, A2 &> a(a1, a2);  
  3.     return l_(type<result_type>(), f_, a, 0); //operator ()  
  4. }  
再次生成一个list2,这个list2中保存的是i1 和 i2的值。接着调用l_.operator() (type<result_type>(), f_, a, 0)函数(还记得l_是什么东东不?)

l_实际是上刚才保存了123和_1的list2!而f_是由bind函数据绑定的函数的指针!

接着看list2的operator() 函数的实现:

  1. template<class R, class F, class A> R operator()(type<R>, F & f, A & a,  
  2.         long) {  
  3.     return f(a[base_type::a1_], a[base_type::a2_]);  
  4. /       return unwrapper<F>::unwrap(f, 0)(a[base_type::a1_], a[base_type::a2_]); //本是这句的,简化了下,无关要紧  
  5. }  
可以看到f是bind所绑定的函数的指针,即这里是调用了我们所绑定的函数。那么参数是从哪里来的?

注意A &a实际上是保存了i1和i2的list2!,所以这里又调用了list2的operator[ ]函数!

再看下list2的operator[] 函数的实现:

  1. A1 operator[](boost::arg<1>) const {  
  2.     cout << "list2  A1 operator[](boost::arg<1>)" << endl;  
  3.     return base_type::a1_;  
  4. }  
  5. A2 operator[](boost::arg<2>) const {  
  6.     cout << "list2  A1 operator[](boost::arg<2>)" << endl;  
  7.     return base_type::a2_;  
  8. }  
  9.   
  10. A1 operator[](boost::arg<1> (*)()) const {  
  11.     cout << "list2  A1 operator[](boost::arg<1> (*)())" << endl;  
  12.     return base_type::a1_;  
  13. }  
  14. A2 operator[](boost::arg<2> (*)()) const {  
  15.     cout << "list2  A1 operator[](boost::arg<2> (*)())" << endl;  
  16.     return base_type::a2_;  
  17. }  
  18.   
  19. template<class T> T & operator[](_bi::value<T> & v) const {  
  20.     cout << "T & operator[](_bi::value<T> & v)" << endl;  
  21.     return v.get();  
  22. }  
貌似问题都解决了,其实这里还有一个关键要素,两个list2是怎么合并起来,组成正确的参数传递给函数f的?(第一个list2存放了123和_1,第二个list2存放了i1和i2)

传递给tow_arguments函数的参数实际是是(123, 1)!

这里要仔细研究这些operator[]函数的实现,才能真正理解其过程。


注意,上面的的代码中bind2只能绑定普通的函数,不能绑定类成员函数,functor,智能指针等。不过其实区别不大,只是增加一些特化的代码而已。

还有一些const相关的函数删掉了。

后记:

从代码可以看到boost::bind和原生的函数指针相比,会损失效率(两次的寻址,函数参数的拷贝,有一些可能没有inline的函数调用)。

不得不吐槽下boost的代码中那些神奇的宏,如果不是IDE有提示,我想真心弄不明白到底哪段是有意义的。。有时候还很神奇地include一部分代码进来(不是头文件,只是实现的一部分!)。

不得不吐槽下模板编程中的const,为了一个函数,比如int sum(int a, int b); 就得写四个重载函数来对应不同参数是或者不是const的情况。所以大家可以想像bind最多支持9个参数,那么有多少种情况了。

boost::bind的实现的确非常精巧,隐藏了很多复杂性。在《C++沉思录》中作者说到世界是复杂的,可以通过复杂性获取简单性。也许这个是对的,但是对于无数的后来的程序员总会有人想要看看黑盒子里到底是什么东东,结果总要花大量的时间才能理解,才能获得这种“简单性”。

C++的模板代码中最痛苦的是到处都是typedef,一个typedef就把所有的类型信息都干掉了!而这东东又是必须的。

也许C++给编程语言技术带来的最大贡献就是牛B的编译器了!

C++11中貌似部分的支持concept,希望这个能简化模板编程。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值