詳細解析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,希望這個能簡化模板編程。


發佈了8 篇原創文章 · 獲贊 32 · 訪問量 30萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章