根据文本文件中提供的类名称创建对象? [英] Create object based on class name provided in text file?

查看:37
本文介绍了根据文本文件中提供的类名称创建对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm wondering, is it possible in C++ to use a text value read in from a file to create an object of a class of that name eg.

contents of file: "MyClass"
code: read file
code: instantiate "MyClass" object.

如果可能的话,我想避免使用一系列硬编码的if/then/elses.抱歉,我不确定如何用更多技术术语来描述此问题!

I'd like to avoid a whole series of hardcoded if/then/elses if possible. Sorry I'm not sure how to describe this problem in more technical terms!

推荐答案

只要您不介意一些限制,就很容易做到.做这项工作的最简单方法是将您限制在一个通用基类的派生类中.在这种情况下,您可以执行以下操作:

As long as you don't mind some restrictions, this is fairly easy to do. The easiest way to do the job restricts you to classes that descend from one common base class. In this case, you can do something like this:

// 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;
};

然后,您显然需要从该基础派生的一些具体类:

You'll then obviously need some concrete classes derived from that base:

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

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

然后,我们需要某种方式来创建每种类型的对象:

Then we need some way to create an object of each type:

functor_base *create_eval_x() { return new eval_x; }
functor_base *create_eval_y() { return new eval_y; }

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

Finally, we need a map from the names to the factory functions:

// 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;

(最终!)给我们足够了,因此我们可以从名称映射到函数对象:

That (finally!) gives us enough so we can map from a name to a function object:

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;

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

There are, of course, many variations on the general theme. For example, instead of factory functions that create objects dynamically, you can create an instance of each object statically, and just put the address of the static object in the map.

这篇关于根据文本文件中提供的类名称创建对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆