In C ++, how to convert a string to a class object?

For example, I have a class called WaterScene, in .xml, which I saved as the string "WaterScene", when I read .xml, I need to convert this string to a class. One approach is just string comparison

if( string == "WaterScene") return new WaterScene; 

Is there a general way to do this to avoid string comparisons? As in object C (dynamic language), we can get the class using the string ...

 Class classObject =[[NSBundle mainBundle] classNamed:string]; 
+4
source share
6 answers

I used the Generic Class factory to solve the problem ... First I register the class and save it on the map until the main ().

0
source

If all the objects you want to return are derived from a common base class, you can use std::map<std::string,BaseClass *> . Comparisons are ultimately out there somewhere, but he keeps things better organized.

+7
source

No, you cannot do this with standard C ++. C ++ has no concept of reflection . Excuse me:)

+4
source

I think you could use an implementation that uses the Abstract Factory Template . Here's a pretty good article on Acceleration in the Spotlight .

+2
source

No. At some level, string comparison should be done in your code. C ++ has no mechanism for such dynamic programming.

0
source

No. But to elegantly get around this limitation, I would list all the possible classes and create an array of the corresponding class names:

 enum ECLASSTYPE { CT_WATER_SCENE, CT_SOME_OTHER, CT__MAX, }; static const string g_classNames[CT__MAX] = { "WaterScene", // CT_WATER_SCENE "SomeOther", // CT_SOME_OTHER }; 

When parsing xml, decode the name of the string to enumerate and pass it to the factory method:

 switch (classType) { case CT_WATER_SCENE: { result = new WaterScene(); break; } ... } 
0
source

All Articles