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

有帮助吗?

解决方案

我喜欢这段 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 标头扩展为内联运算符()定义列表。例如,最简单的:

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 往往是参数类型列表。还存在许多复杂情况,因为对于不同数量的参数,存在不少于九次的重载。最好不要过多地纠缠于此。

其他提示

顺便说一下,如果通过包含 boost / bind / bind_template.hpp 来折叠和简化 bind_t ,就会更容易理解如下:

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_;

};

我认为它是一个模板类,它为你想要绑定的参数声明一个成员变量,并为其余参数重载()。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top