c ++实体组件系统和使用模板访问组件

c++ entity component system and accessing components using a template

我一直致力于创建自己的实体组件系统,并且我准备通过执行以下操作来获取组件:

const auto& component = entity->GetComponent<ComponentType>();

上面的函数看起来像这样:

template <typename TyComponent>
TyComponent* Entity<T>::GetComponent() const
{
  return &(GetComponent(TyComponent::Id());
}

然后 returns 如果找到一个基于关联 id 的组件,否则 nullptr.

  1. 我正在做的事情可行吗?
  2. 有没有办法确保只能从 Component 派生的类型 用作 GetComponent?
  3. 的参数

这个设计还可以。

如果有人尝试 GetComponent<Foo>,您将已经收到编译时错误,但 Foo 没有静态 Id() 函数。所以这会给你一点安全感。

但是,它仍然需要修改一下才能编译。这是我的做法:

Component * GetComponent(int id) { ... }

template <typename TyComponent>
TyComponent* Entity<T>::GetComponent() const {
  return dynamic_cast<TyComponent*>(GetComponent(TyComponent::Id()));
}

TyComponent 不是从 Component 派生时,这现在将生成编译错误。 (组件至少需要一个虚函数才能工作。)