使用模板将std :: shared_ptr <Derived>转换为std :: shared_ptr <Base>

时间:2020-03-30 11:18:48

标签: c++ templates shared-ptr upcasting

我在继承链中有4个类:A-> B-> C,A-> B-> D,其中B是唯一的类模板。

我想拥有一个在id和对象指针(C或D)之间映射的std :: map,但是我很难将make_shared输出分配给std :: map上的一个条目。

有趣的是,另一个类似的示例,但没有中间模板类,正在编译OK,所以我想这与此有关。

#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;
}

编译器错误:

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

1 个答案:

答案 0 :(得分:2)

您尝试的conversion依是在班级及其子代之外的。它不能工作,因为继承是非公开的。要解决此问题,请公开继承。或者,在成员函数中进行转换。