我需要一种基于作为 std::string 传递的类名来实例化对象的方法。这现在有效,但需要概括:
void* create(std::string name) {
if(name == "classOne") return new ClassOne();
else if(name == "classTwo") return new ClassTwo();
/* ... */
}
我没有的:
- 控制要实例化的类:可以是 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
}
作为一个方面,也许是无关紧要的注意事项,考虑到要实例化的对象可能来自一个类或一个结构。
附加信息
我看到需要更多的上下文。这是我的特定用例,简化:
// 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
}
附加信息
我正在使用带有最新 GNU 编译器的 C++11。