C++通用对象工厂按字符串名称

yio*_*own 5 c++

我需要一种基于作为std :: string传递的类名来实例化对象的方法.这项目前正在发挥作用,但需要进行概括:

void* create(std::string name) {
    if(name == "classOne") return new ClassOne();
    else if(name == "classTwo") return new ClassTwo();
    /* ... */
}
Run Code Online (Sandbox Code Playgroud)

我没有的东西:

  • 控制要实例化的类:可能是30个派对类.不能对这些类进行任何更改(即基本祖先,多态创建者方法等...)
  • 全班名单列表:以后可以添加更多类,不应该对此工厂进行更改.
  • 要实例化的类周围的包装:由于前两点.

还有别的什么.

最佳用例场景将是:

int main() {
    void *obj = create("classTree"); // create object based on the string name
    /* ... */
    // once we know by context which specific class we are dealing with
    ClassTree *ct = (ClassTree*)obj; // cast to appropiate class
    std::cout << ct->getSomeText() << std::endl; // use object
}
Run Code Online (Sandbox Code Playgroud)

作为一个侧面,也许是不相关的注释,考虑到要实例化的对象可能来自类或结构.

添加信息

我看到需要更多的背景.这是我的特定用例,简化:

// registration mechanism
int main() {
    std::map< std::string, void(*func)(std::string, void*) > processors; // map of processors by class name
    processors["ClassFour"] = (void(*)(std::string, void*)) &classFourMessageProcessor; // register processor (cast needed from specific to generic)
}
// function receiving string messages
void externalMessageHandler(std::string msg) {
    std::string objType = extractTypeFromMessageHeader(msg); // extract type from message
    // now that we know what we are dealing with, create the specific object
    void *obj = create(objType); // << creator needed
    processors[objType](msg, obj); // dispatch message to process
}
// previously registered message processor
void classFourMessageProcessor(std::String msg, ClassFour *obj) {
    std::string streetAddress = msg.substr(10, 15); // knowing the kind of message we can extract information
    obj->moveTheEtherTo(streetAddress); // use the created object
}
Run Code Online (Sandbox Code Playgroud)

添加信息

我正在使用C++ 11和最新的GNU编译器.

Ale*_*ler 5

您可以为每个类类型存储一个工厂函数。一个简单的方法是使用模板

template <typename T>
void* creator() {
  return new T();
}
Run Code Online (Sandbox Code Playgroud)

并将它们存储在地图中(即“ClassFour”链接到creator<ClassFour>和 到ClassFourMessageProcessor)。

编辑:为了澄清,processors成为

typedef void* (*CreatorFunc)();
typedef void (*ProcessorFunc)(std::string, void*);

typedef std::pair<CreatorFunc, ProcessorFunc> Entry;
std::map< std::string, Entry > processors;
Run Code Online (Sandbox Code Playgroud)

添加一个新类就像

processors["SomeClass"] = Entry(creator<SomeClass>, ClassFourMessageProcessor);
Run Code Online (Sandbox Code Playgroud)