How can I use Unique_ptrs with an class object having std::function as argument in the constructor
auto bPtr = std::unique_ptr<B>(new B( std::function< std::unique_ptr<A>() > () ));
// need to close the template ^
// need to construct an instance of ^^
You get the same a bit simpler by using std::make_unique
:
auto bPtr = std::make_unique<B>( std::function< std::unique_ptr<A>() >() );
// still as above ^^^
Edit: Adjustment to new question version:
You have not yet provided a copy constructor – so you need to store the lambda instead of creating a B
instance:
auto l = []() { return std::make_unique<A>(); };
auto bPtr = std::unique_ptr<B>(new B(l));
// or:
auto ptr = std::make_unique<B>(l);
Note that this new edited version provides a factory function to the std::function
object (the lambda!), while the initial variants constructed an empty one without function stored inside, so not callable!
You might construct a B by passing a std::function
(or value which might convert to).
For example appropriate lambda:
B b{[]() { return std::make_unique<A>(); }};
If you really want std::unique_ptr<B>
, then it becomes:
std::unique_ptr<B> b = std::make_unique<B>([]() { return std::make_unique<A>(); });