bind的本質:就是建立一個Functor對象(重載了operator()的類對象)
經過將多餘的函數參數和函數指針存儲爲Funtor對象的成員變量,在調用operator()函數是,利用存儲的函數指針和函數參數,返回相應的結果
建立Functor對象
> BoostPrj.exe!bind_test() Line 60 + 0x16 bytes C++
#include
auto
myf = boost::bind(f, 1, 2);
//或者 boost::function myf = boost::bind(f, 1, 2);
myf();
// boost/bind/bind.hpp的代碼
#ifndef
BOOST_BIND
#define
BOOST_BIND bind
#endif
#define
BOOST_BIND_CC
#define
BOOST_BIND_ST
#include
#undef
BOOST_BIND_CC
#undef
BOOST_BIND_ST
------------------第二層
BoostPrj.exe!boost::bind(int* f, void a1, bool a2) Line 39 + 0x59 bytes C++
//bind/bind_cc.hpp
template
<
class
R,
class
B1,
class
B2,
class
A1,
class
A2>
_bi::bind_t
BOOST_BIND_ST R (BOOST_BIND_CC *) (B1, B2),
typename _bi::list_av_2::type> //返回的Functor類型
BOOST_BIND(BOOST_BIND_ST R (BOOST_BIND_CC *f) (B1, B2), A1 a1, A2 a2)
{
typedef BOOST_BIND_ST R (BOOST_BIND_CC *F) (B1, B2);
typedef typename _bi::list_av_2::type list_type;
return _bi::bind_t (f, list_type(a1, a2));
}
此時:a1=1,a2=2
boost::_bi::bind_t<
int, //R
int (__cdecl*)(int,int),//F 函數指針f
boost::_bi::list2,boost::_bi::value > //list_type 存儲2個函數參數
>//返回的Functor類型
--------------------
> BoostPrj.exe!boost::_bi::bind_t,boost::_bi::value > >::bind_t,boost::_bi::value > >(int* f, void l) Line 870 C++
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
#undef BOOST_BIND_RETURN
};
//boost/bind/bind_template.hpp
result_type operator()() const
{
list0 a;
BOOST_BIND_RETURN l_(type(), f_, a, 0);
}
private:
F f_;//存儲函數指針
L l_;//存儲函數參數
int //R
int (__cdecl*)(int,int)//F
boost::_bi::list2,boost::_bi::value > //L
----------------list_type(a1,a2)的推導過程 第三層
BoostPrj.exe!
boost::_bi::list2,boost::_bi::value >::
list2,boost::_bi::value >
(boost::_bi::value a1, boost::_bi::value a2)
Line 283 + 0x13 bytes C++
//bind/bind.hpp
template<class A1, class A2> struct list_av_2
{
typedef typename add_value::type B1; //第1
typedef typename add_value::type B2;
typedef list2 type;
};
A1和A2爲int,B1和B2的類型經以下推導爲_bi::value
----------------------
template< class T, int I > struct add_value_2
{
typedef boost::arg type;
};
template< class T > struct add_value_2< T, 0 >//第4
{
typedef _bi::value< T > type;
};
template<class T> struct add_value //第2
{
typedef typename add_value_2< T, boost::is_placeholder< T >::value >::type type;
};
T爲int,boost::is_placeholder< T >::value 爲0
//boost/is_placeholder.hpp
template< class T > struct is_placeholder
{
enum _vt { value = 0 };//第3
};
--------------------------------
template<class T> class value{
public:
value(T const & t): t_(t) {}
T & get() { return t_; }
T const & get() const { return t_; }
bool operator==(value const & rhs) const{
return t_ == rhs.t_;
}
private:
T t_;
};
-----------
template< class A1, class A2 > class list2: private storage2< A1, A2 >{
private:
typedef storage2< A1, A2 > base_type;
public:
list2( A1 a1, A2 a2 ): base_type( a1, a2 ) {}
//
};
A1和A2都是boost::_bi::value
爲list2,boost::_bi::value >