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

后端 未结 7 2131
予麋鹿
予麋鹿 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 09:55

    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.

提交回复
热议问题