Skip to content

Instantly share code, notes, and snippets.

@SammyJames
Created April 7, 2017 21:25
Show Gist options
  • Save SammyJames/2e4718a770a8a892adc7fc012ea1a1a7 to your computer and use it in GitHub Desktop.
Save SammyJames/2e4718a770a8a892adc7fc012ea1a1a7 to your computer and use it in GitHub Desktop.
enum class ComponentType : unsigned
{
Invalid,
Transform,
}
class Component
{
virtual ComponentType GetType() const = 0;
};
#define COMPONENT_TYPE(Type) \
public: \
ComponentType StaticType() { return Type; } \
ComponentType GetType() override { return StaticType(); }
class TransformComponent : public Component
{
COMPONENT_TYPE(ComponentType::Transform)
public:
void SetPosition(...);
};
class Entity
{
public:
template <typename T>
T* GetComponent() const
{
ComponentType key = T::StaticType();
Component* value = m_components[ key ];
return static_cast<T*>(value);
}
template <typename T, typename... Args>
T* AddComponent(Args&&... inArgs)
{
Component*& newComponent = m_components[ key ];
newComponent = new T(std::forward<Args>(inArgs)...);
return static_cast<T*>(newComponent);
}
private:
std::unordered_map<ComponentType, Component*> m_components;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment