c++ - 如何实例化一个只知道其名称的对象?

标签 c++ class reflection instantiation

<分区>

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");

关于c++ - 如何实例化一个只知道其名称的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8269465/

相关文章:

c++程序在字符数组中插入单词

c++ - 编译 SFML 2.0 项目时加载共享库时出错

c++ - 将 Vector 与类一起使用时没有运算符错误

javascript - 在 TypeScript 中凝胶化一个类的所有模型属性

c++ - 初学者的错误

c++ - 多线程 C++,将带有参数的函数从类传递到 main

c++ - 使用友元函数重载算术运算符

json - 使用反射在 Go 中创建 map

scala - Scala 2.10 可以提供哪些反射功能?

c++ - 如何使用 C++ 在 Linux 中检查 USB 端口并提供设备(内存等)信息