0

在尝试用 C++ 创建实体组件系统时,由于缺乏对语言的了解,我遇到了一些问题。

使用一个类Entity,它包含接口IComponent(它的作用更像是一个表示“我持有数据”的标志),我有一个方法Add,如果没有同一个类的另一个 IComponent 已经在它。

这是一个过于简化的示例代码:

struct IComponent{};

struct Foo : IComponent{ int x;};
struct Bar : IComponent{ int y; };

class Entity{
    vector<IComponent*> entityComponents;

    void Add(IComponent* componentToAdd){
        if("entityComponents" does not contain the class of "componentToAdd")
            entityComponents.add (componentToAdd)

    }
}

我的预期结果是

Entity e;
Foo f;
Bar b;
Foo anotherF;

e.Add(f); // Works
e.Add(b); // Works
e.Add(anotherF); // Does not work because another 
                 //item in the array already inherits Foo

但我不知道如何从 IComponents 列表中获取 Foo 和 Bar 的基类并检查它们是否重复。

我怎样才能得到它们?如果 Foo 在 IComponent 列表中,我如何将 IComponent 转换为 Foo?

4

2 回答 2

1

Checkout dynamic_cast. You can attempt to cast a pointer to base class to a pointer to a derived class. It fails if the instantiated object is not of type derived and in this case returns null.

于 2019-06-24T05:49:38.973 回答
1

As Bar Stool stated, my solution was

template<typename T>
bool HasComponent(){
  for(Component* component: this->components)
        if(T* casted = dynamic_cast<T*>(component))
                return true;           
  return false;

}

And later just check if "HasComponent()" is false and then add it

于 2019-06-24T22:43:09.937 回答