从包含C ++中类名的字符串动态创建类的实例 [英] Dynamically creating an instance of a class from a string containing the class name in C++

查看:215
本文介绍了从包含C ++中类名的字符串动态创建类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个有100个孩子的基类:

Lets say I have a base class with 100 children:

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)。现在我将迭代这些字符串,创建一个特定孩子的实例,并用它的特定喂养程序喂它:

At runtime I want to read a file that contains which children to create and feed. Lets say I've read the file and the vector of strings "names" contains the names of the child classes (ie. Child1, Child4, Child99). Now I'm going to iterate through these strings, create an instance of the specific child, and feed it with its specific feeding procedure:

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它返回一个新的Child1,如果字符串参数是Child4它返回一个新的Child4等

How would I create the function convert_string_to_instance() such that if it takes in the string "Child1" it returns a "new Child1", if the string argument is "Child4" it returns a "new Child4", etc

<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 ++不提供方法用于类实例的动态构造。但是,您可以使用代码生成从类列表中生成强力代码(如上所示)。然后, #include convert_string_to_instance 方法中生成的代码。

C++ does not provide a method for dynamic construction of class instances like this. However, you may be able to use code generation to generate the "brute force" code (like you showed above) from a list of classes. Then, #include the generated code in your convert_string_to_instance method.

您还可以设置项目构建系统,以便在类列表更改时重新生成生成的代码。

You can also set up your project build system to rebuild the generated code anytime the list of classes changes.

这篇关于从包含C ++中类名的字符串动态创建类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆