【发布时间】:2016-11-08 21:03:46
【问题描述】:
我正在修改实体组件系统的实体管理器。由于组件没有重叠的功能,我不希望它们有一个我可以存储的共享库。
所以我想出了这样的东西:
#include <vector>
#include <memory>
#include <iostream>
class Component1{};
class Component2{};
class Component3{};
class Manager{
public:
template<typename T> static std::vector<std::shared_ptr<T>> component;
template<typename T> static std::shared_ptr<T> getComponent(int nth){
return component<T>[nth];
}
template<typename T> static std::shared_ptr<T> addComponent(int nth){
return component<T>[nth] = shared_ptr<T>(new T());
}
static void addEntity(){
// push back a nullptr for every instantiated component<>
}
static void removeEntity(int nth){
// set the nth index of every component<> to nullptr
}
};
template<typename T>
std::vector<std::shared_ptr<T>> Manager::component = std::vector<std::shared_ptr<T>>();
int main(){
Manager::component<Component1>;
Manager::component<Component2>;
Manager::component<Component3>;
Manager::addEntity();
auto cmp2 = Manager::getComponent<Component2>(0);
Manager::removeEntity(0);
std::cin.get();
return 0;
}
如何迭代两个函数的实例化组件?尝试使用 type_info 的向量来存储组件类型,但我永远无法从中获取正确的类型以用作模板参数。
【问题讨论】: