给出A类,
class A {
public:
A(B&) {}
};
我需要一个boost::function<boost::shared_ptr<A>(B&)>
对象。
我不想创建ad-hoc功能
boost::shared_ptr<A> foo(B& b) {
return boost::shared_ptr<A>(new A(b));
}
解决我的问题,我正在尝试解决它绑定lambda :: new_ptr。
boost::function<boost::shared_ptr<A> (B&)> myFun
= boost::bind(
boost::type<boost::shared_ptr<A> >(),
boost::lambda::constructor<boost::shared_ptr<A> >(),
boost::bind(
boost::type<A*>(),
boost::lambda::new_ptr<A>(),
_1));
也就是说,我分两步绑定A的new_ptr和shared_ptr的构造函数。显然它不起作用:
/usr/include/boost/bind/bind.hpp:236: error: no match for call to ‘(boost::lambda::constructor<boost::shared_ptr<A> >) (A*)’
/usr/include/boost/lambda/construct.hpp:28: note: candidates are: T boost::lambda::constructor<T>::operator()() const [with T = boost::shared_ptr<A>]
/usr/include/boost/lambda/construct.hpp:33: note: T boost::lambda::constructor<T>::operator()(A1&) const [with A1 = A*, T = boost::shared_ptr<A>]
我应该如何进行绑定呢? 提前致谢, 弗朗西斯
答案 0 :(得分:3)
使用boost::lambda::bind
代替boost::bind
。
#include <boost/shared_ptr.hpp>
#include <boost/lambda/bind.hpp> // !
#include <boost/lambda/construct.hpp>
#include <boost/function.hpp>
void test()
{
using namespace boost::lambda;
boost::function<boost::shared_ptr<A>(B&)> func =
bind( constructor< boost::shared_ptr<A> >(), bind( new_ptr<A>(), _1 ) );
}