【问题标题】:Upcasting std::shared_ptr<Derived> to std::shared_ptr<Base> with templates使用模板将 std::shared_ptr<Derived> 向上转换为 std::shared_ptr<Base>
【发布时间】:2020-03-30 11:18:48
【问题描述】:

我在一个继承链中有 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

【问题讨论】:

  • protected 继承?不是public?

标签: c++ templates shared-ptr upcasting


【解决方案1】:

您尝试的转换不在该类及其子类之外。它不能工作,因为继承是非公开的。要修复它,请将继承公开。或者,在成员函数中进行转换。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-06
    • 2010-11-24
    • 2021-06-21
    • 2021-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-20
    相关资源
    最近更新 更多