根据文本文件中提供的类名创建对象?

Pet*_*233 3 c++

我想知道,在C++中是否可以使用从文件读入的文本值来创建该名称类的对象,例如.

contents of file: "MyClass"
code: read file
code: instantiate "MyClass" object.
Run Code Online (Sandbox Code Playgroud)

如果可能的话,我想避免使用一系列硬编码if/then/elses.对不起,我不知道如何用更多技术术语来描述这个问题!

Jer*_*fin 8

只要你不介意一些限制,这很容易做到.执行此任务的最简单方法是将您限制为从一个公共基类继承的类.在这种情况下,您可以执行以下操作:

// warning: I've done this before, but none of this code is tested. The idea 
// of the code works, but this probably has at least a few typos and such.
struct functor_base { 
    virtual bool operator()() = 0;
};
Run Code Online (Sandbox Code Playgroud)

那么你显然需要一些从这个基础派生的具体类:

struct eval_x : functor_base { 
   virtual bool operator()() { std::cout << "eval_x"; }
};

struct eval_y : functor_base {
    virtual bool operator()() { std::cout << "eval_y"; }
};
Run Code Online (Sandbox Code Playgroud)

然后我们需要一些方法来创建每种类型的对象:

functor_base *create_eval_x() { return new eval_x; }
functor_base *create_eval_y() { return new eval_y; }
Run Code Online (Sandbox Code Playgroud)

最后,我们需要一个从名称到工厂函数的映射:

// the second template parameter is:
// pointer to function returning `functor_base *` and taking no parameters.
std::map<std::string, functor_base *(*)()> name_mapper;

name_mapper["eval_x"] = create_eval_x;
name_mapper["eval_y"] = create_eval_y;
Run Code Online (Sandbox Code Playgroud)

那个(终于!)给了我们足够的,所以我们可以从一个名称映射到一个函数对象:

char *name = "eval_x";

// the map holds pointers to functions, so we need to invoke what it returns 
// to get a pointer to a functor:
functor_base *b = name_mapper.find(name)();

// now we can execute the functor:
(*b)();

// since the object was created dynamically, we need to delete it when we're done:
delete b;
Run Code Online (Sandbox Code Playgroud)

当然,一般主题有很多变化.例如,您可以静态地创建每个对象的实例,而只是将静态对象的地址放在地图中,而不是动态创建对象的工厂函数.