2009-02-09 82 views
80

我不喜欢让魔术盒散布在我的代码中......这两个类究竟如何工作,基本上允许任何函数映射到函数对象,即使函数<>具有完全不同的参数设置为所述一个即时传递到boost::bindboost :: function和boost :: bind如何工作

它甚至用不同的调用约定有效(即构件的方法是__thiscall VC下,但“正常”的功能是通常对于那些需要__cdecl__stdcall与C兼容。

+0

Dupe:http://stackoverflow.com/questions/112738/how-does-boost-bind-work-behind-the-scenes-in-general – 2009-02-09 08:59:59

+1

不是真的 - 这个问题是关于绑定和功能 – 2009-02-09 09:15:39

回答

94

boost::function允许任何与operator()将正确的签名绑定为参数,并且可以使用参数int调用绑定的结果,因此它可以绑定到function<void(int)>

这是如何工作的(这描述适用一样为std::function):

boost::bind(&klass::member, instance, 0, _1)返回这样

struct unspecified_type 
{ 
    ... some members ... 
    return_type operator()(int i) const { return instance->*&klass::member(0, i); 
} 

其中return_typeint从的klass::member签名推断的对象,并且函数指针和绑定参数实际上存储在对象中,但这不重要

现在,boost::function确实不做任何类型检查:它将采用您在其模板参数中提供的任何对象和任何签名,并根据您的签名创建可调用的对象并调用该对象。如果这是不可能的,这是一个编译错误。

boost::function实际上是这样的对象:

template <class Sig> 
class function 
{ 
    function_impl<Sig>* f; 
public: 
    return_type operator()(argument_type arg0) const { return (*f)(arg0); } 
}; 

其中return_typeargument_typeSig萃取,f在堆上动态分配的。这需要允许完全不相关的不同尺寸的物体绑定到boost::function

function_impl仅仅是一个抽象类

template <class Sig> 
class function_impl 
{ 
public: 
    virtual return_type operator()(argument_type arg0) const=0; 
}; 

,做所有的工作类,是从boost::function派生的具体类。有一个为每个分配到boost::function

template <class Sig, class Object> 
class function_impl_concrete : public function_impl<Sig> 
{ 
    Object o 
public: 
    virtual return_type operator()(argument_type arg0) const=0 { return o(arg0); } 
}; 

这意味着你的情况类型的对象,分配给Boost功能:

  1. 实例(当然这是编译的时候,)一类function_impl_concrete<void(int), unspecified_type>
  2. 创建该类型在堆上
  3. 的新对象分配此目的是升压的f-构件::函数

当您调用函数对象时,它会调用其实现对象的虚函数,该函数会将调用引导至您的原始函数。

免责声明:请注意,此解释中的名称是故意组成的。与真人或角色的任何相似......你知道它。目的是说明原则。

相关问题