背景和基本原理简介
我正在设计一个编译时 ECS。该设计有它的细节——例如,会有各种各样的实体。这意味着组件的总数可能相当高,而每个实体的组件数量将相当低(有一些明显的几乎无处不在的公共(public)元素,例如 Sprite
或 BoundingBox
)
我的方法
我将实现以下接口(interface):
/* Tell the compiler which fields we would use in this entity */
Entity<GraphicsComponent, PhysicsComponent> entity;
/* Populate the handles with the appropriate data (integer, pointer, doesn't matter) */
// via explicit creation
Entity.add<GraphicsComponent>(RenderSystem::create<GraphicsComponent>());
// or in some other way?
我编写的Entity
类的开始:
template <typename ...>
class Entity final {};
但是,我不知道如何为相应的组件类型创建句柄数据字段,以及是否有可能。任何人都可以帮助我或解释为什么它不起作用(或者可能建议不同的解决方案)?
最佳答案
只需使用std::tuple
。注意: get
要求每个 Components...
都是不同的类型
template <typename ... Components>
class Entity final {
std::tuple<Components...> components;
template<typename Component>
void add(Component component) // possibly cv / ref qualified
{
std::get<std::decay_t<Component>>(components) = component;
}
};
关于c++ - 如何使用模板创建编译时类字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47284529/