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

Given class A,

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

I need an object boost::function<boost::shared_ptr<A>(B&)>.

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 am trying to solve it by 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 from A and the shared_ptr constructor. Obviously this does not 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 do I bind instead? Thanks in advance, Francesco

+3
source share
1 answer

Use boost::lambda::bindinstead 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 ) );
}
+3
source

Source: https://habr.com/ru/post/1763472/


All Articles