Possible Duplicate:
Is there a way to instantiate objects from a string holding their class name?
在 C++ 中,我想让我的用户输入要在运行时创建的对象类型名称,并且根据我从他们那里得到的字符串,程序将实例化正确的对象(简而言之,我是实现工厂方法模式)。但是,如果程序必须支持新的对象类型,则不允许修改现有代码。
那么是否有可能从方法中删除所有 if...else if...else if... 内容,并且仍然让我的程序实例化特定产品类型的正确对象(在许多,其中仅在编译时已知)?
我四处搜索找到了这个链接:Is there a way to instantiate objects from a string holding their class name? 看起来这就是我想要的,但我根本看不懂代码。
非常感谢任何帮助。
只有当所有必需的类都派生自某个公共(public)基类时,这才会起作用,并且您通常只能使用基接口(interface)(尽管您可以通过一些额外的努力来解决这个问题)。这是一种方法:
// Immutable core code:
#include <map>
#include <string>
class Base
{
typedef Base * (*crfnptr)(const std::string &);
typedef std::map<std::string, crfnptr> CreatorMap;
static CreatorMap creators;
public:
virtual ~Base() { }
Base * clone() const { return new Base(*this); }
static Base * create_from_string(std::string name)
{
CreatorMap::const_iterator it = creators.find(name);
return it == creators.end() ? NULL : it->first();
}
static void register(std::string name, crfnptr f)
{
creators[name] = f;
}
};
现在您可以从新代码中添加新的派生类:
// your code:
#include "immutable_core.hpp"
class Foo : public Base
{
public:
Foo * clone() const { return new Foo(*this); }
static Foo * create() { return new Foo; }
};
Base::register("Foo", &Foo::create);
要创建一个类,您只需调用 Base * p = Base::create_from_string("Foo");
。