2008-09-22 24 views

回答

24

我喜歡這片bind來源:

template<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 

}; 

告訴你幾乎所有你需要知道的,真的。

bind_template標題擴展爲內嵌operator()定義的列表。例如,最簡單的:

result_type operator()() 
{ 
    list0 a; 
    BOOST_BIND_RETURN l_(type<result_type>(), f_, a, 0); 
} 

我們可以在這一點上看到BOOST_BIND_RETURN宏展開return太行更像return l_(type...)

的一個參數的版本是在這裏:

template<class A1> result_type operator()(A1 & a1) 
{ 
    list1<A1 &> a(a1); 
    BOOST_BIND_RETURN l_(type<result_type>(), f_, a, 0); 
} 

這是非常相似的。

listN類是參數列表的包裝。這裏有很多深刻的魔法,但我並沒有真正理解太多。他們還重載了operator(),稱之爲神祕的unwrap功能。忽略一些特定的編譯器過載,它不會做了很多:

// unwrap 

template<class F> inline F & unwrap(F * f, long) 
{ 
    return *f; 
} 

template<class F> inline F & unwrap(reference_wrapper<F> * f, int) 
{ 
    return f->get(); 
} 

template<class F> inline F & unwrap(reference_wrapper<F> const * f, int) 
{ 
    return f->get(); 
} 

的命名規則似乎是:F是函數參數bind的類型。 R是返回類型。 L往往是參數類型的列表。還有很多複雜因素,因爲對於不同數量的參數,重複次數不會少於9次。最好不要多說這些。

+2

這似乎並不簡單,我... 爲什麼是`#定義BOOST_BIND_RETURN返回'必要? 爲什麼不只是返回? – Ha11owed 2011-09-10 14:33:00

0

我認爲這是一個模板類,它爲要綁定的參數聲明一個成員變量,爲其餘參數聲明一個成員變量,併爲其重載。

2

順便說一句,如果bind_t被摺疊並簡化了通過包括boost/bind/bind_template.hpp,它變得更容易理解這樣的:

template<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) {} 

     typedef typename result_traits<R, F>::type result_type; 
     ... 
     template<class A1> 
      result_type operator()(A1 & a1) 
      { 
       list1<A1 &> a(a1); 
       return l_(type<result_type>(), f_, a, 0); 
      } 
    private: 
     F f_; 
     L l_; 

};