c++ - 使用模板将std::shared_ptr <Derived>上载到std::shared_ptr <Base>

标签 c++ templates shared-ptr upcasting

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

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

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

#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

最佳答案

您尝试的转换不在类(class)及其子级范围内。它不能工作,因为继承是非公开的。要解决此问题,请公开继承。或者,在成员函数内进行转换。

关于c++ - 使用模板将std::shared_ptr <Derived>上载到std::shared_ptr <Base>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60929415/

相关文章:

C++ 允许我在运行时分配一个数组而不是给出一个错误

c++ - 可重载的 boost::asio::basic_stream_socket

c++ - 从静态成员函数推断类模板参数的模式

c++ - 模板函数使用参数包时如何传递其他模板参数?

c++ - enable_shared_from_this 需要什么?

C++ 方法覆盖

c++ - C++ 中 Pascal 字符串的数据布局

templates - GoLang 在模板索引中挂起

python - 在 python 扩展中操作来自 SWIG 的共享指针

c++ - 使用 std::move 和 std::shared_ptr 有什么好处和风险(如果有的话)