【发布时间】:2011-06-04 02:23:52
【问题描述】:
假设我有一个有 100 个孩子的基类:
class Base {
virtual void feed();
...
};
class Child1 : public Base {
void feed(); //specific procedure for feeding Child1
...
};
...
class Child100 : public Base {
void feed(); //specific procedure for feeding Child100
...
};
在运行时,我想读取一个文件,其中包含要创建和提供的子项。假设我已经阅读了该文件,并且字符串“names”的向量包含子类的名称(即 Child1、Child4、Child99)。现在我将遍历这些字符串,创建特定孩子的实例,并使用其特定的喂养程序喂养它:
vector<Base *> children;
for (vector<string>::iterator it = names.begin(); it != names.end(); ++it) {
Base * child = convert_string_to_instance(*it)
child->feed()
children.push_back(child);
}
我将如何创建函数 convert_string_to_instance() 以便如果它接受字符串“Child1”它返回一个“new Child1”,如果字符串参数是“Child4”它返回一个“new Child4”等等
<class C *> convert_string_to_instance(string inName) {
// magic happens
return new C; // C = inName
// <brute force?>
// if (inName == "Child1")
// return new Child1;
// if (inName == "Child2")
// return new Child2;
// if (inName == "Child3")
// return new Child3;
// </brute force>
}
【问题讨论】:
-
C++ 中闻起来像折射的动态类。如果没有“蛮力”尝试,我不知道该怎么做。我很想知道怎么做。
-
基本上是这样的:stackoverflow.com/questions/41453/… 有一些系统可以进行像这样的高级反射:root.cern.ch/drupal/content/reflex,但它们都需要额外的构建步骤来提取元数据
-
这将是我一段时间以来在 StackOverflow 上看到的最精巧的问题。恰到好处的细节,我喜欢
部分。可悲的是,我认为该主题的变化是唯一的答案。
标签: c++ dynamic new-operator instance