c++ - 一般来说,boost bind 在幕后是如何工作的?

标签 c++ boost boost-bind

无需花很长时间查看 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 header 扩展为内联 operator() 定义的列表。比如最简单的:

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 类是参数列表的包装器。这里有很多深奥的魔法,虽然我不太了解。他们还重载了调用神秘的 unwrap 函数的 operator()。忽略一些编译器特定的重载,它并没有做很多事情:

// 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 往往是参数类型的列表。还有很多复杂性,因为对于不同数量的参数有不少于九个重载。最好不要过多关注。

关于c++ - 一般来说,boost bind 在幕后是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/112738/

相关文章:

c++ - 如何终止DLL中的log4cplus?

c++ - 删除存储在数组中的特定类对象

C++ 标准委员会 "reflector"邮件列表

c++ - 有没有办法用 MIDL 关闭 C 风格的头文件生成?

c++ - 如何使用 Boost 和 C++ 递归地单独列出文件和文件夹

C++:所有 boost 路径操作段错误(Ubuntu/g++)

c++ - boost C++ 序列化/反序列化

c++ - boost::bind 静态函数的参数

c++ - 使用 boost::function::target 获取函数指针时的空指针

c++ - token 解析器语义操作