Using boost::bind and boost::lambda::new_ptr to return a shared_ptr constructor

十年热恋 提交于 2019-12-22 10:38:23

问题


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


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!