dvilela
dvilela

Reputation: 1262

Upcasting std::shared_ptr<Derived> to std::shared_ptr<Base> with templates

I have 4 classes in an inheritance chain: A->B->C, A->B->D, where B is the only class template.

I would like to have an std::map that maps between ids and object pointers (C or D), but I'm having trouble assigning the make_shared output to an entry on the std::map.

The funny thing is that another similar example, but without an intermediate template class is compiling OK, so I guess it has to do with that.

#include <iostream>
#include <map>
#include <memory>

class A
{
    public:
        int i;
    protected:
        A(int j) : i(j) {}
};

template <typename T>
class B : protected A
{
    protected:
        T t;
        B(int i) : A(i) {}
};

class C : protected B<int>
{
    public:
        C(int i) : B(i) {}
};

class D : protected B<float>
{
    public:
        D(float i) : B(i) {}
};

int main()
{
    std::map<std::string, std::shared_ptr<A>> map; // [id, object ptr]

    map["c"] = std::make_shared<C>(0); // error here
    map["d"] = std::make_shared<D>(1.0); // error here

    for (auto i : map)
    {
        std::cout << i.first << i.second->i << std::endl;
    }

    return 0;
}

The compiler error:

main.cpp:37:37: error: no match for ‘operator=’ (operand types are ‘std::map<std::__cxx11::basic_string<char>, std::shared_ptr<A> >::mapped_type {aka std::shared_ptr<A>}’ and ‘std::shared_ptr<C>’)
     map["c"] = std::make_shared<C>(0); // error

Upvotes: 2

Views: 288

Answers (1)

eerorika
eerorika

Reputation: 238321

Your attempted conversion is outside of the class and its children. It cannot work because the inheritance is non-public. To fix it, make the inheritance public. Alternatively, do the conversion within a member function.

Upvotes: 3

Related Questions