7

寻找一种避免大量 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");
}
4

4 回答 4

5

如果您的编译器与 C++11 兼容,您可以使用 lambda 和 轻松做到这一点std::map

#include <iostream>
#include <string>
#include <map>
#include <functional>

using namespace std;

struct BaseClass {virtual void foo()=0;};
struct DerivedClass1 : public BaseClass {void foo() {cout << "1" << endl;}};
struct DerivedClass2 : public BaseClass {void foo() {cout << "2" << endl;}};

// Here is the core of the solution: this map of lambdas does all the "magic"
map<string,function<BaseClass*()> > factory {
    {"one", [](){return new DerivedClass1();}}
,   {"two", [](){return new DerivedClass2();}}
};

int main() {
    BaseClass *a = factory["one"](); // Note the function call () at the end
    BaseClass *b = factory["two"]();
    a->foo();
    b->foo();
    delete a;
    delete b;
    return 0;
}

这个想法是制作一个地图,为您提供一个创建适当子类的函数。

ideone 上的演示

于 2013-07-20T13:12:26.007 回答
3

首先,语法入门:

struct Base {
    virtual ~Base() {} // do not forget this if you need polymorphism
};

然后,一个“工厂”功能:

template <typename T>
std::unique_ptr<Base> makeBase() { return std::unique_ptr<Base>(new T{}); }

这个函数的类型是:

using BaseMaker = std::unique_ptr<Base>(*)();

最后,把它放在一起:

struct DerivedOne: Base {}; struct DerivedTwo: Base {};

using BaseMakerMap = std::map<std::string, BaseMaker>;

BaseMakerMap const map = { { "DerivedOne", makeBase<DerivedOne> },
                           { "DerivedTwo", makeBase<DerivedTwo> } };

std::unique_ptr<Base> makeFromName(std::string const& n) {
    BaseMakerMap::const_iterator it = map.find(n);

    if (it == map.end()) { return std::unique_ptr<Base>(); } // not found

    BaseMaker maker = it->second;

    return maker();
}
于 2013-07-20T12:57:09.243 回答
1

您应该能够执行以下操作:

template<class C>
BaseClass * makeObject<C> () {
    return new C;
}

struct LookupList {
    const char* name;
    BaseClass * (*factoryFunction) ();
};

LookupList list [] = {
    {"ClassOne", &makeObject<DerivedClassOne>},
    {"ClassTwo", &makeObject<DerivedClassTwo>}
};

...

... instantiateFromString ...
    return list[i].factoryFunction ();

但是,我更喜欢 Map 而不是LookupList. 此外,您可能想熟悉 C++11 中的函数式语法。

于 2013-07-20T12:54:06.683 回答
0

你不能像这样初始化你的列表。

typedef struct
{
    const char *name;
    BaseClass class;
} LookupList;

LookupList list[] = {
    {"ClassOne", DerivedClassOne},
    {"ClassTwo", DerivedClassTwo}
};

list.class 是一个 BaseClass 对象,而初始值是 DerivedClassOne,它是一个类。那没有意义。你会得到编译器错误。

于 2013-07-20T12:37:33.847 回答