Given a class A,
class A {
public:
A(B&) {}
};
I need a boost::function<boost::shared_ptr<A>(B&)>
object.
I prefer not to create an ad-hoc function
boost::shared_ptr<A> foo(B& b) {
return boost::shared_ptr<A>(new A(b));
}
to solve my problem, and I'm trying to solve it binding 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));
that is, I bind in two steps the new_ptr of a A and the constructor of shared_ptr. Obviously it doesn't work:
/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>]
How should I do the binding instead? Thanks in advance, Francesco
Use boost::lambda::bind
instead of 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 ) );
}
来源:https://stackoverflow.com/questions/3652476/using-boostbind-and-boostlambdanew-ptr-to-return-a-shared-ptr-constructor