我正在尝试将一些称为组件的数据附加到实体节点。
但是,每当我将派生组件类型附加到Entity节点时,它都会被提升为基本Component
类型而不是保留子节点。我怎么能阻止这个,所以我可以使用std::type_index
?
目前,由于组件正在升级,std::type_index
不断为Component
创建索引,而不是其中一个子类。我是否需要模板AttachComponent
方法?我不愿意。
class Entity final
{
//Typedefs
typedef std::map<std::type_index, std::shared_ptr<acorn::Component> > ComponentMap;
ComponentMap m_components;
unsigned long int m_ID;
private:
public:
explicit Entity(unsigned long int id);
~Entity();
//Getters
inline unsigned long int GetID() const
{
return m_ID;
}
template<class ComponentType>
std::weak_ptr<ComponentType> GetComponent()
{
auto component_map_it = m_components.find(std::type_index(typeid(ComponentType)));
//If the component was found
if (component_map_it != m_components.end()) {
//Get the shared_ptr of the component
std::shared_ptr<acorn::Component> base_ptr = component_map_it->second;
//Cast it to the desired component type
std::shared_ptr<ComponentType> converted_ptr(std::static_pointer_cast<ComponentType>(base_ptr));
//Convert to a weak pointer
std::weak_ptr<ComponentType> return_ptr(converted_ptr);
//Return the weak pointer
return return_ptr;
}
else {
//If no component type was found, return a nullptr.
return std::weak_ptr<ComponentType>();
}
}
//Setters
inline void AttachComponent(std::shared_ptr<Component> component)
{
auto raw_ptr = component.get();
auto insert_pair = std::make_pair(std::type_index(typeid(raw_ptr)), component);
m_components.insert(insert_pair);
}
};`
答案 0 :(得分:1)
是的,你必须让AttachComponent
成为一个模板。这是保留类型信息的唯一方法:
template <class T>
void AttachComponent(std::shared_ptr<T> component)
{
// as before
}