C++ 向上广播标准::共享\u ptr<;派生>;至标准::共享\u ptr<;基地>;使用模板
我在继承链中有4个类:A->B->C,A->B->D,其中B是唯一的类模板 我希望有一个在ID和对象指针(C或D)之间映射的std::map,但在将make_共享输出分配给std::map上的条目时遇到了问题 有趣的是,另一个类似的示例,但没有中间模板类,可以编译,所以我想这与此有关C++ 向上广播标准::共享\u ptr<;派生>;至标准::共享\u ptr<;基地>;使用模板,c++,templates,shared-ptr,upcasting,C++,Templates,Shared Ptr,Upcasting,我在继承链中有4个类:A->B->C,A->B->D,其中B是唯一的类模板 我希望有一个在ID和对象指针(C或D)之间映射的std::map,但在将make_共享输出分配给std::map上的条目时遇到了问题 有趣的是,另一个类似的示例,但没有中间模板类,可以编译,所以我想这与此有关 #include <iostream> #include <map> #include <memory> class A { public: int i
#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;
}
#包括
#包括
#包括
甲级
{
公众:
int i;
受保护的:
A(intj):i(j){}
};
模板
B类:受保护的A类
{
受保护的:
T;
B(inti):A(i){}
};
C类:受保护的B类
{
公众:
C(int i):B(i){}
};
D类:受保护的B类
{
公众:
D(浮动i):B(i){}
};
int main()
{
标准::映射映射;//[id,对象ptr]
map[“c”]=std::make_shared(0);//此处出错
map[“d”]=std::make_shared(1.0);//此处出错
用于(自动i:map)
{
std::cout您尝试的转换在类及其子类之外。它无法工作,因为继承是非公共的。若要修复它,请将继承设置为公共的。或者,在成员函数内执行转换。受保护的
继承?非公共的
?
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