#include <iostream>
#include <vector>
#include <memory>
#include <unordered_map>
using namespace std;
struct A { void what_type() { cout<<"A"<<endl; }};
struct B { void what_type() { cout<<"B"<<endl; }};
class MyCommonAncestor {
};
template <class T>
class MyTemplateClass : public MyCommonAncestor {
public:
std::unordered_map<int, T> myx;
};
int main() {
vector<shared_ptr<MyCommonAncestor>> myVector;
myVector.push_back(make_shared<MyTemplateClass<A>>());
myVector.push_back(make_shared<MyTemplateClass<B>>());
for (auto& x: myVector)
x->myx; // just for the shake of this example
return 0;
}
我如何找到一种方法来从myx
中实际访问MyTemplateClass
成员变量,从而保持模板的使用,因为我需要它。我收到以下错误:
error: ‘class MyCommonAncestor’ has no member named ‘myx’
最佳答案
您可以将指针动态转换为模板类。但是继承的要点是将共性放入您的基类中,否则它们存在的意义是什么。
关于c++ - 访问父类的子模板类的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65075389/