我正在修改實體組件系統的實體管理器。由於組件沒有重疊的功能,我不希望它們擁有我可以存儲的共享基礎。跟蹤實例化的模板類型C++
所以我想出了這樣的事情:
#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的向量來存儲組件類型,但我永遠無法從它們中獲取適當的類型以用作模板參數。