如何实现支持多参数的C++ Component多类工厂
组件工厂扩展需求及现有实现
我需要实现一个签名如下的类工厂:
Component* (GameObject*, ...)
当前ComponentFactory实现
.h 文件
#pragma once // Dependencies | std #include <functional> #include <vector> #include <utility> // Dependencies | CoreEngine #include "Component.h" #include "GameObject.h" class ComponentFactory { // Object public: // Properties std::vector<std::pair<const type_info*, std::function<Component* (GameObject* gameObject)>>> factory = std::vector<std::pair<const type_info*, std::function<Component* (GameObject*)>>>(); // Constructor / Destructor ComponentFactory(); ~ComponentFactory(); // Functions void addRegistry(const type_info* typeInfo, std::function<Component* (GameObject*)> contructor); Component* create(GameObject* gameObject, const type_info* typeInfo); };
.cpp 文件
#include "ComponentFactory.h" // class ComponentFactory // Object | public // Constructor / Destructor ComponentFactory::ComponentFactory() { } ComponentFactory::~ComponentFactory() { } // Functions void ComponentFactory::addRegistry(const type_info* typeInfo, std::function<Component* (GameObject*)> constructor) { std::pair<const type_info*, std::function<Component* (GameObject*)>> registry = std::pair<const type_info*, std::function<Component* (GameObject*)>>(typeInfo, constructor); factory.push_back(registry); } Component* ComponentFactory::create(GameObject* gameObject, const type_info* typeInfo) { for (const std::pair<const type_info*, std::function<Component* (GameObject*)>>& registry : factory) if (registry.first == typeInfo) return registry.second(gameObject); return nullptr; }
现有问题与扩展需求
当前代码的局限性在于:部分Component的构造函数除了GameObject*外,还需要其他任意数量、任意类型的参数。我需要工厂支持返回Component*,且第一个参数固定为GameObject*,后续可接收任意参数,签名形式如下:
Component* (GameObject*, ...)
核心目标
向组件工厂传入const type_info*、GameObject实例及对应构造参数,最终得到Component*指针。
注意事项
- 组件工厂必须是实例对象,因为需要创建多个不同的组件工厂,并在大型代码中构建“has a”关联关系。
Component是所有组件类的基类。- 每个
Component对象及其子类都包含一个const type_info* typeInfo成员变量。
期望调用形式
componentFactory.create(gameObject, *typeid(someClass), ...)
配套JSON配置示例
读取以下JSON文件后,将根据其中内容创建对象,其中type字段存储的是type_info.name(),后续会与组件工厂中存储的type_info进行匹配:
{ "gameObjects": [ { "id": 1, "name": "Camera Game Object", "transform": { "position": [ 0.0, 0.0, 0.0 ], "rotation": [ 0.0, 0.0, 0.0 ], "scale": [ 1.0, 1.0, 1.0 ] } } ], "transformRelationships": null, "components": [ { "gameObjectIndex": 0, "type": "class Camera2D", "data": { "graphicsContextIndex": 0, "viewSize": 16.0, "backgroundColor": [ 0.15000000596046448, 0.15000000596046448, 0.15000000596046448, 1.0 ] } }, { "gameObjectIndex": 0, "type": "class CameraController", "data": { "strength": 1.0 } }, { "gameObjectIndex": 0, "type": "class GameObjectController", "data": { "strenght": 0.10000000149011612 } }, { "gameObjectIndex": 0, "type": "class EmptyComponent", "data": {} } ] }
内容的提问来源于stack exchange,提问作者Christopher Barrios Agosto
相关产品推荐
相关产品推荐

