使用未知模板类型列表创建库

时间:2014-01-04 00:05:11

标签: c++ templates wrapper component-based

前段时间,我开始制作游戏,我遇到了一种我非常喜欢的风格。它被称为基于组件的体系结构。本教程适用于Objective-C,而不是C ++,但我还是包含了链接: http://www.raywenderlich.com/24878/introduction-to-component-based-architecture-in-games

我注意到我正在复制并粘贴从项目到项目的大量代码,所以我决定只为一般框架创建一个库。通常,组件包含在实体对象中,如下所示:

#ifndef ENTITY_H
#define ENTITY_H

#include "HealthComponent.h"
#include "MoveComponent.h"
#include "PlayerComponent.h"
#include "RenderComponent.h"

class Entity
{
public:
    Entity();

    HealthComponent* getHealth();
    //Returns a reference to the object's health component
    //If there is none, returns a null pointer

    MoveComponent* getMove();
    //Returns a reference to the object's movement component
    //If there is none, returns a null pointer

    PlayerComponent* getPlayer();
    //Returns a reference to the object's player component
    //If there is none, returns a null pointer

    RenderComponent* getRender();
    //Returns a reference to the object's render component
    //If there is none, returns a null pointer

    ~Entity();
private:
    HealthComponent* health;
    MoveComponent* move;
    PlayerComponent* player;
    RenderComponent* render;
};

#endif //ENTITY_H

由于我的库将包含通用框架,而不是单个组件,因此该方法不再适用。相反,我创建了一个ComponentManager类来管理我的组件。目前,实体看起来像这样:

#ifndef ENTITY_H
#define ENTITY_H

#include "Component.h"
#include "ComponentManager.h"
#include <list>

class Entity
{
public:
    Entity();
    Entity(ComponentManager const & cmanager);
    template <T>
    T* getComponent();
    //Returns the first component of the specified type
    //If there is none, returns NULL

    template <T>
    T* getComponent(int i);
    //Returns the ith component of the specified type
    //If the component does not exist, returns NULL

    template<T>
    int getComponentCount();
    //Returns the number of components of the specific type that the
    //entity contains

    template <T>
    int addComponent(T &component);
    //Adds a component of the specified type to the class. If a component of the
    //class already exists, the component is assigned a number, and the number is returned.
    //If no components of the class exist, 0 is returned

    ~Entity();
private:
    int eid;
    std::list<ComponentReference> components;
    ComponentManager * manager;
};

#endif //ENTITY

我还没有定义这些功能,所以我没有包含implimentation文件。

ComponentReference结构只是用于定位特定组件的整数和字符串的集合。实体会将ComponentReference传递给manager中的模板化函数,该函数将在其内部列表中搜索特定对象。还有砖墙。我不知道如何创建一个包含不同数量的不同未知类型对象的列表。它们派生自父Component类,但它们都包含不同的函数和成员变量。我尝试使用指针和类型转换的数组,但是当我读到过度依赖类型转换是代码编写错误的指示时,我放弃了三个小时。

我尝试使用STL容器,但它们只需要一种类型,所以显然它们不起作用 (C++ std::vector with pointers to a template class

我看到了一些关于包装器的东西,但是根据我的阅读,它们似乎只能用于函数:(c++ store a pointer to a member function of unknown class)如果它们可以用于解决我的问题,请解释它们是如何工作的(我从来没有在今天之前听说过他们)

由于这是我的第一个问题,请随时留下反馈。我做了研究,但如果这是重复的,我很抱歉。我不是C ++的新手,但我也不是专家,而且它是一门大语言,所以我可能会要求澄清。提前谢谢!

0 个答案:

没有答案