Dynamically creating an instance of a class from a string containing the class name in C++

后端 未结 7 1993
予麋鹿
予麋鹿 2020-12-31 09:00

Lets say I have a base class with 100 children:

class Base { 
  virtual void feed();
  ...   
};
class Child1 : public Base {
  void feed();  //specific proc         


        
相关标签:
7条回答
  • 2020-12-31 10:04

    If you have a lot of classes, you'd usually choose a less brute force approach. A trie or hash_map between class names and factory functions is a good approach.

    You can use a codegen approach as suggested by Greg to build this factory table, for example doxygen can parse your source code and output a list of all classes in xml format along with inheritance relationships, so you could easily find all classes deriving from a common "interface" base class.

    0 讨论(0)
提交回复
热议问题