0

i have the following problem: I have a map of unique pointers. The unique pointers type is a base class. Now i want to make a copy of this map. I tried something like this:

#include <map>
#include <memory>

class A
{
    virtual void myFunc()=0;
};

class B : public A
{
    float b;
public:
    virtual void myFunc() override
    {
        b=1.0;
    }
};


int main()
{
    std::map<int,std::unique_ptr<A>> myMap;
    std::map<int,std::unique_ptr<A>> myMapCopy;

    myMap.emplace(1,std::make_unique<B>());
    for(auto& itMyMap : myMap)
    {
        myMapCopy.emplace(itMyMap.first,std::make_unique<A>(*itMyMap.second));
    }
}

Problem is, that I have to specify the type when calling make_unique, but I don't know if its a B or any other derived class. Is there some nice trick to make deep copies of a unique pointer without specializations?

wychmaster
  • 712
  • 2
  • 8
  • 23

0 Answers0