如何只知道其名称来实例化对象?

Icy*_*now 5 c++ reflection class instantiation

可能重复:
有没有办法从保存其类名的字符串中实例化对象?

在C++中,我想让我的用户输入要在运行时创建的对象类型名称,并且,根据我从它们获得的字符串,程序将实例化正确的对象(简而言之,我正在实现工厂方法图案).但是,如果程序必须支持新的对象类型,则不允许修改现有代码.

那么是否有可能从方法中删除所有if ... else if ... else if ...的东西,并且仍然让我的程序实例化特定产品类型的正确对象(在众多中,只有已知的在编译时)?

我的搜索给了我这个链接:有没有办法从持有类名的字符串中实例化对象?它似乎是我想要的,但我根本无法理解代码.

任何帮助将非常感激.

Ker*_* SB 5

这只有在所有必需的类都是从某个公共基类派生的情况下才有效,并且您通常只能使用基本接口(尽管您可以通过一些额外的工作来解决这个问题).这是一种方法:

// 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;
  }
};
Run Code Online (Sandbox Code Playgroud)

现在,您可以从新代码中添加新的派生类:

// 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);
Run Code Online (Sandbox Code Playgroud)

要创建一个类,只需调用即可Base * p = Base::create_from_string("Foo");.