bind_t模板定義在bind.hpp中:
#ifndef BOOST_NO_VOID_RETURNStemplate<class R, class F, class L> class bind_t{public: typedef bind_t this_type; bind_t(F f, L const & l): f_(f), l_(l) {}#define BOOST_BIND_RETURN return#include <boost/bind/bind_template.hpp>#undef BOOST_BIND_RETURN};#else
因為實現代碼很多,放在一個hpp檔案中,並且在bind_t內部用include引入該檔案。這種用法挺有意思。
其中成員變數是:
private: F f_; L l_;
因此bind_t建構函式將參數f和l儲存到私人變數中。
同時定義了兩個類型:
typedef bind_t this_type; typedef typename result_traits<R, F>::type result_type;
這裡result_type就是R
緊接著提供了一堆operator()(T...) 的重載操作符。
T可以是void, 也可以是多個boost::arg<N>參數:
result_type operator()() { list0 a; BOOST_BIND_RETURN l_(type<result_type>(), f_, a, 0); } result_type operator()() const { list0 a; BOOST_BIND_RETURN l_(type<result_type>(), f_, a, 0); }
這兩個是無參的形式。
l_() 這句就是調用了operator()()函數。說明l_就是個function object.
並且把代表無參數的list0對象a傳遞進去。
template<class A1> result_type operator()(A1 & a1) { list1<A1 &> a(a1); BOOST_BIND_RETURN l_(type<result_type>(), f_, a, 0); } template<class A1> result_type operator()(A1 & a1) const { list1<A1 &> a(a1); BOOST_BIND_RETURN l_(type<result_type>(), f_, a, 0); }
這兩個和前面的差不多,就是多了個參數,反如list1中,然後調用l_變數的operator()().
template<class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9> result_type operator()(A1 & a1, A2 & a2, A3 & a3, A4 & a4, A5 & a5, A6 & a6, A7 & a7, A8 & a8, A9 & a9) { list9<A1 &, A2 &, A3 &, A4 &, A5 &, A6 &, A7 &, A8 &, A9 &> a(a1, a2, a3, a4, a5, a6, a7, a8, a9); BOOST_BIND_RETURN l_(type<result_type>(), f_, a, 0); } template<class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9> result_type operator()(A1 & a1, A2 & a2, A3 & a3, A4 & a4, A5 & a5, A6 & a6, A7 & a7, A8 & a8, A9 & a9) const { list9<A1 &, A2 &, A3 &, A4 &, A5 &, A6 &, A7 &, A8 &, A9 &> a(a1, a2, a3, a4, a5, a6, a7, a8, a9); BOOST_BIND_RETURN l_(type<result_type>(), f_, a, 0); }
這兩個是接收9個參數的形式。
總結:模板bind_t接受兩個參數,一個是用來執行的函數f(或者函數指標等形式),一個是function object l.
同時提供了很多operator()()來接收從0-9的不同數目的參數,內部都通過執行function object l的operator()()來運行f, 參數由運行時外部調用程式傳入。
也提供了accept支援visitor模式。
return type也可以由外部程式指定,作為模板參數R傳遞給bind_t.
這裡有個調用的例子:
typedef typename _bi::list_av_1<A1>::type list_type;return _bi::bind_t<R, F, list_type> (f, list_type(a1));
所以這時候l參數就是list_type(a1),也就是list_av_1<a1>::type, 也就是list1<a1>, 此時a1就是_1,因此A1就是boost::arg<1>類型。