在不花很长时间回顾boost源代码的情况下,有人能给我简要介绍一下boost bind是如何实现的吗?
发布于 2008-09-21 20:10:20
我喜欢这段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
往往是参数类型的列表。还有很多复杂的问题,因为对于不同数量的参数,至少有9个重载。最好不要在这上面纠结太多。
发布于 2009-12-03 13:10:26
顺便说一下,如果通过包含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_;
};
发布于 2008-09-21 17:19:42
我认为它是一个模板类,它为要绑定的参数声明了一个成员变量,并为其余参数声明了overload ()。
https://stackoverflow.com/questions/112738
复制相似问题