I read Passing shared_ptr<Derived> as shared_ptr<Base> but that doesn't answer my question.
Suppose we have
class Base
{
};
class Derived : public Base
{
};
I would like to create the following container: std::map<int, std::shared_ptr<std::unordered_map<std::string, std::shared_ptr<Base>>>> _channels;
I need to add instances as values with types std::shared_ptr<std::unordered_map<std::string, std::shared_ptr<Base>>>
and std::shared_ptr<std::unordered_map<std::string, std::shared_ptr<Derived>>>
.
Unfortunately I'm unable to add instances with Derived
type, but with type Base
it's fine.
Full code:
#include <iostream>
#include <string>
#include <map>
#include <unordered_map>
#include <memory>
#include <utility>
class Base
{
};
class Derived : public Base
{
};
int main()
{
// works fine
/*
std::map<int, std::shared_ptr<Base>> _channels2;
_channels2.emplace(std::pair<int, std::shared_ptr<Derived>>(3, std::make_shared<Derived>()));
std::cout << "_channels2.size() = " << _channels2.size() << std::endl;
*/
// fails to compile
std::map<int, std::shared_ptr<std::unordered_map<std::string, std::shared_ptr<Base>>>> _channels;
_channels.emplace(std::pair<int, std::shared_ptr<std::unordered_map<std::string, std::shared_ptr<Derived>>>>(2, std::make_shared<std::unordered_map<std::string, std::shared_ptr<Derived>>>()));
std::cout << "_channels.size() = " << _channels.size() << std::endl;
return 0;
}
I'm using C++14.
Am I understand well so the reason behind it fails to compile is because
std::shared_ptr<std::unordered_map<std::string, std::shared_ptr<Derived>>>
is not a subtype ofstd::shared_ptr<std::unordered_map<std::string, std::shared_ptr<Base>>>
? So polymorphism isn't available in this case.Is there a workaround you can advise?
Thank you.