3

I'm trying to create a functor that returns a shared_ptr by calling std::bind on std::make_shared, but the syntax is beyond me, or perhaps it's not even possible? Something like the following, assuming the constructor of MyBar takes a const reference to a MyFoo:

std::function<std::shared_ptr<MyBar>(const MyFoo &)> functor = std::bind(&std::make_shared<MyBar>, std::placeholders::_1);
tgoodhart
  • 3,111
  • 26
  • 37

1 Answers1

7

You're nearly there; you just need to specify the additional arguments to make_shared to indicate the type of parameter it accepts. These are normally deduced, but if you don't specify them in a bind expression then it tries to default-construct the MyBar object.

std::function<std::shared_ptr<MyBar>(const MyFoo &)> functor = 
    std::bind(&std::make_shared<MyBar,MyFoo const&>, std::placeholders::_1);
Anthony Williams
  • 66,628
  • 14
  • 133
  • 155