gpt4 book ai didi

c++ - 从 String 到 Type (C++) 的最佳方式是什么

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:47:29 24 4
gpt4 key购买 nike

我希望能够将类型指定为字符串并在 C++ 中创建该类型。我知道 C++ 不直接支持它,但解决这个问题的最佳方法是什么?

我目前有一个包含信息的 xml,但我想扩展它以包含组件。

<entity>
<component>ComponentA</component>
<component>ComponentB</component>
</entity>

我有一个通用工厂,它接受这些 xml 并构建实体。我希望能够避免 if("componentA") { new ComponentA; } 支持更通用的东西。主要是因为组件将由客户定义,而工厂不是。

我认为组件可以向工厂注册自己并存储 map ,但这需要持有所有我想避免的组件的拷贝。

我更喜欢跨平台解决方案。

最佳答案

据我所知,至少对于通用 C++,没有隐式方法可以仅使用字符串来创建类。但是,我过去曾使用过另一种机制。

首先,您定义组件的概念:

class Component /* or IComponent if you're feeling adventurous - we may not have interfaces in C++, but dammit we like 'em! */
{
protected:
Component() { };

public:
virtual ~Component() = 0 { };
}; // eo class Component

以及某种创作者的概念:

class ComponentCreator
{
protected:
Component() { };

public:
virtual ~ComponentCreator() = 0 { };
virtual Component* create() const = 0; // Might want to use smart-pointers here - this is for illustrative purposes only.
}; // eo class ComponentCreator

好的,我们有了基础知识,现在我们需要一个可以让这些创作者注册的工厂:

class Factory
{
private:
std::map<std::string, ComponentCreator*> _creators;

public:
Factory() : _creators(new std::map<std::string, ComponentCreator*>();
{
};

~Factory()
{
// cleanup of _creators ommited.
};

// call to register a creator
void register(const std::string& name, ComponentCreator* creator)
{
// normally you'd put checks to see if it exists etc.
_creators[name] = creator;
}; // eo register


// call to create an instance
Component* create(const std::string& name)
{
std::map<std::string, ComponentCreator*>::const_iterator cit(_creators.find(name));
if(cit != _creators.end())
return cit->create();
else
return NULL; // or nullptr
}; // eo create
}; // eo class Factory

这样声明你的类(我只做一个):

class ComponentA : public Component { /* implementation */ };

不要忘记创作者:

class ComponentCreatorForA : public ComponentCreator
{
public:
virtual Component* create() const { return new ComponentA(); };
}; // eo class ComponentCreatorForA

在程序初始化期间,您注册组件创建者:

factory.register("componentA", new ComponentCreatorForA());
factory.register("componentB", new ComponentCreatorForB());

稍后,我们可以按名称创建组件:

Component* component = factory.create("componentA");

注意事项:

  • 此方法假定组件在编译时是已知的。如果没有人可以引入一种插件架构,以便其他 DLL 可以在启动时通过工厂注册它们的组件,这样您就可以使其可扩展而无需重新部署所有内容。

  • 在现实世界中,我们会使用一些这样的智能指针,并使用 typedef 去掉很多这样的东西,以便打字更容易!

关于c++ - 从 String 到 Type (C++) 的最佳方式是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20119509/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com