I'm trying to map
a components type to the component value itself in a map
. The following code all works properly. My main question is this. Is storing the map
key as std::type_info*
the best way to accomplish what I'm doing? I'm also not digging the ugly static_cast<T*>
I'm doing during the usage part.
Entity.h
#pragma once
#include "IComponent.h"
#include <map>
#include <typeinfo>
class Entity
{
public:
Entity(void);
~Entity(void);
void AddComponent(IComponent* component);
IComponent* GetComponent(const std::type_info* typeInfo);
private:
std::map<const std::type_info*, IComponent*> components;
};
Entity.cpp
#include "Entity.h"
Entity::Entity(void)
{
}
Entity::~Entity(void)
{
for (auto &mapValue : components)
{
delete mapValue.second;
}
}
void Entity::AddComponent(IComponent* component)
{
const type_info* info = &typeid(*component);
components.insert (std::pair<const std::type_info*,IComponent*>(info, component));
}
IComponent* Entity::GetComponent(const std::type_info* typeInfo)
{
return components.at(typeInfo);
}
Example Usage
IComponent* baseComponent = entity->GetComponent(&typeid(PerkList));
PerkList* perkList = static_cast<PerkList*>(baseComponent);
typeid
return and object with static storage. It will last for the lifetime of the program. \$\endgroup\$type_index
? Seems more adequate for what you are doing and can be used with anunordered_map
. (C++11) \$\endgroup\$type_index
is exactly what I was looking for and is meant as a clean wrapper for all thetype_info
usage in this case. Thank you! \$\endgroup\$