一般而言,boost bind 是如何在幕后工作的?

2021-12-24 00:00:00 c++ boost boost-bind

无需花很长时间查看 boost 源代码,有人可以简要介绍一下 boost 绑定是如何实现的吗?

Without spending a long time reviewing the boost source code, could someone give me a quick rundown of how boost bind is implemented?

推荐答案

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

};

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

Tells you almost all you need to know, really.

bind_template 标头扩展为内联 operator() 定义列表.比如最简单的:

The bind_template header expands to a list of inline operator() definitions. For example, the simplest:

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

我们可以看到 BOOST_BIND_RETURN 宏此时扩展为 return,所以该行更像是 return l_(type...).

We can see the BOOST_BIND_RETURN macro expands to return at this point so the line is more like 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 类是参数列表的包装器.这里有很多深奥的魔法,但我并不太了解.他们还重载了调用神秘的 unwrap 函数的 operator().忽略一些编译器特定的重载,它不会做很多事情:

The listN classes are wrappers for the parameter lists. There is a lot of deep magic going on here that I don't really understand too much though. They have also overloaded operator() that calls the mysterious unwrap function. Ignoring some compiler specific overloads, it doesn't do a lot:

// 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();
}

命名约定似乎是:Fbind 的函数参数的类型.R 是返回类型.L 往往是一个参数类型列表.还有很多复杂性,因为不同数量的参数有不少于九个重载.最好不要想太多.

The naming convention seems to be: F is the type of the function parameter to bind. R is the return type. L tends to be a list of parameter types. There are also a lot of complications because there are no less than nine overloads for different numbers of parameters. Best not to dwell on that too much.

相关文章