【发布时间】: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