2010-09-06 38 views
3

鉴于A类,使用boost ::绑定和boost ::拉姆达:: new_ptr返回一个shared_ptr的构造

class A { 
public: 
    A(B&) {} 
}; 

我需要一个boost::function<boost::shared_ptr<A>(B&)>对象。

我不想建立一个特设的功能

boost::shared_ptr<A> foo(B& b) { 
    return boost::shared_ptr<A>(new A(b)); 
} 

解决我的问题,我试图解决它结合拉姆达:: 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>] 

我应该怎么做绑定呢? 在此先感谢, Francesco

+0

这是一个完美的例子,表明lambda实际上使整个事情不必要地变得更加复杂,除了增加编译时间之外没有其他好处。 C++的限制可能被推得太多了。 – kizzx2 2010-10-07 13:03:45

回答

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)); 
} 
相关问题