寻找一种避免大量 IF/ELSE 的方法,并使用查找表将字符串解析为要实例化的特定类,这些类都派生自基类。这样的事情是否可能,如果可以,怎么做?
typedef struct BaseClass
{
} BaseClass;
typedef struct DerivedClassOne : BaseClass
{
} DerivedClassOne;
typedef struct DerivedClassTwo : BaseClass
{
} DerivedClassTwo;
typedef struct
{
const char *name;
BaseClass class;
} LookupList;
LookupList list[] = {
{"ClassOne", DerivedClassOne},
{"ClassTwo", DerivedClassTwo}
};
BaseClass *InstantiateFromString(char *name)
{
int i;
for (i = 0; i < 2; i++)
{
if (!strcmp(name, list[i].name))
return new list[i].class();
}
}
int main (int argc, char *argv[])
{
BaseClass *myObjectFromLookup = InstantiateFromString("ClassOne");
}