【问题标题】:c++ entity component system and accessing components using a templatec++实体组件系统和使用模板访问组件
【发布时间】:2015-09-21 22:14:13
【问题描述】:

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

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

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

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

如果找到,则返回基于关联 id 的组件,否则返回 nullptr

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

【问题讨论】:

    标签: c++ c++11 templates components entity-component-system


    【解决方案1】:

    这个设计还可以。

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

    但是,它仍然需要进行一次更改才能编译。这是我的做法:

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

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

    【讨论】:

    • static_cast&lt;Component*&gt; 不足以进行编译时检查吗?
    • @πάνταῥεῖ 你是对的。在这种情况下,您可以使用static_cast 逃脱,但如果出现问题,我更喜欢获得 NULL 的额外安全性而不是获得未定义的行为......
    猜你喜欢
    • 2018-01-05
    • 2013-07-24
    • 2018-08-13
    • 1970-01-01
    • 2016-01-23
    • 2020-10-18
    • 2014-07-06
    • 2019-05-03
    • 2018-08-17
    相关资源
    最近更新 更多