当类名存储在另一个变量中时,如何创建类的实例 [英] How to create instance of a class when the class name is stored in another variable
问题描述
可能重复:
C ++中的最小反射
基本上我有类名存储在 char *
,如何创建该类的实例。
以下是我在想什么。当我通过 Test
作为模板参数这是很好,但如果我尝试这样 Test * t = CreateType< ptr>
它不会工作。
Basically I have class name stored in char *
, how Do i create instance of that class.
Following is what I was thinking. It works when I pass Test
as template parameter which is fine, but if I try something like this Test *t = CreateType<ptr>
it will not work.
有任何方法使这项工作。
Is there any way to make this work.
class Test{
public:
Test() {
}
~Test() {
}
};
template <typename T>
T* CreateType() {
return new T;
}
int main ( int argc, char **argv) {
char *ptr = "Test";
Test *T = CreateType<Test>();
return 0;
}
推荐答案
直接可能在C ++中,因为语言不是内省的。
It is not directly possible in C++, because the language is not introspective.
您可以尝试做类似的 。例如,您可以使用地图< string,baseClassPointer>
其中键将是类的名称,并且该值将是指向该类对象的指针。然后,您可以通过从地图复制对象(您可以通过类型名称获取)创建其他对象。我不建议做这样的事情,虽然。
You can try to do something similar though. For example, you can have a map< string, baseClassPointer >
where the key will be the class' name, and the value will be a pointer to that class' object. Then you can create other objects by copying an object from the map (which you can get by the type name). I wouldn't suggest doing things like that though.
工厂模式可以满足您的需求。
Factory pattern may suit your needs though.
这篇关于当类名存储在另一个变量中时,如何创建类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!