一般而言,增强绑定在后台如何工作?
时间:2020-03-06 14:31:11 来源:igfitidea点击:
无需花费大量时间查看boost的源代码,有人可以给我快速介绍一下boost绑定是如何实现的吗?
解决方案
我认为这是一个模板类,它为要绑定的参数声明一个成员变量,并为其余参数重载()。
我喜欢这个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头扩展为内联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(); }
命名约定似乎是: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_; };