In C++ how to convert a string to class object?
For example i have a class named "WaterScene", in the .xml i have saved as string "WaterScene" when i read the .xml i have to convert that string to class. One approach is just string comparison
if( string == "WaterScene")
return new WaterScene;
Is there any generic way to do this to avoid string comparison? Like in objective C(dynamic language) we ca开发者_如何学Pythonn get the class using string...
Class classObject =[[NSBundle mainBundle] classNamed:string];
If all of the objects you would be returning are derived from a common base class, you could use a std::map<std::string,BaseClass *>
. The comparisons ultimately in there somewhere, but it keeps things better organized.
No, you can't do it with standard C++. C++ has no notion of reflection. Sorry :)
I think you could probably use an implementation that leverages the Abstract Factory Pattern. Here is a pretty good article on a Boost centric implementation.
No. At some level, a string comparison must be done in your code. C++ doesn't have any mechanism for that kind of dynamic programming.
No. But to elegantly get around this limitation I would enumerate all possible classes and create an array of 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 string name to enum and pass it to the factory method:
switch (classType)
{
case CT_WATER_SCENE:
{
result = new WaterScene();
break;
}
...
}
I have used Generic Class factory to solve the issue... First i am registering class and storing it in a map before main().
精彩评论