一般来说,boost绑定如何在幕后工作?

Bri*_*ndy 32 c++ boost boost-bind

如果不花很长时间来审查boost源代码,有人可以快速了解一下boost bind的实现方式吗?

180*_*ION 25

我喜欢这个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

};
Run Code Online (Sandbox Code Playgroud)

告诉你几乎所有你需要知道的,真的.

bind_template头扩展到内联的列表operator()定义.例如,最简单的:

result_type operator()()
{
    list0 a;
    BOOST_BIND_RETURN l_(type<result_type>(), f_, a, 0);
}
Run Code Online (Sandbox Code Playgroud)

我们可以看到BOOST_BIND_RETURNreturn在这一点扩展到所以线更像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);
}
Run Code Online (Sandbox Code Playgroud)

它非常相似.

这些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();
}
Run Code Online (Sandbox Code Playgroud)

命名约定似乎是:F是函数参数的类型bind.R是返回类型.L往往是参数类型列表.还存在许多复杂情况,因为对于不同数量的参数,存在不少于九次的重载.最好不要过多地纠缠于此.

  • 这对我来说似乎并不简单...为什么`#define BOOST_BIND_RETURN返回'必要?为什么不回来? (2认同)
  • @ Ha11owed因为这样他们可以使用标题来获得没有返回值的模板! (2认同)