I'm still new to C++ and have come across a problem where I can't seem to insert a new derived class to a map.
My code is simplified as follows:
std::map<int, std::unique_ptr<Base_Class> > m;
void func(){
for(int num = 0; num < 100; n++){
m.emplace(num, new Derived_Class() );
}
}
Which gives me this:
error: no matching function for call to 'std::pair <const int, std::unique_ptr<Base_Class> >::pair(int&, Derived_Class*)
I've tried unsuccessfully using:
m.emplace(std::pair(num, new Derived_Class()) );
And which gives me this:
error: no matching function for call to 'std::pair<const int, std::unique_ptr<Base_Class> >::pair(std::pair<int, Derived_Class*>)
I can't seem to figure this one out and would appreciate any help.
m.emplace(num, std::unique_ptr<Derived_Class>(new Derived_Class()));
Would be the way to go. Since the unique_ptr
constructor taking a raw pointer is explicit, it cannot be implicitly initialized from a Derived_Class*
. You need to explicitly create a unique_ptr
object to emplace.
I posed this solution because you mentioned c++11, but the truly favorable way would be to use std::make_unique<Derived_Class>()
(c++14 and onward), both to avoid repeating yourself, and to make the creation of the unique_ptr "atomic".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With