Skip to content

Instantly share code, notes, and snippets.

@christianparpart
Created February 24, 2014 15:37
Show Gist options
  • Save christianparpart/9190619 to your computer and use it in GitHub Desktop.
Save christianparpart/9190619 to your computer and use it in GitHub Desktop.
clang++ -std=c++11 -o comps comps.cpp
#include <stdio.h>
#include <typeinfo>
#include <unordered_map>
class Foo {
public:
void dump() { printf("Hello, foo!\n"); }
};
class Bar {
public:
void dump() { printf("Hello, bar!\n"); }
};
class Entity { // {{{
public:
template<typename T, typename... Args>
void addComponent(Args&... args);
template<typename T>
T* getComponent();
private:
std::unordered_map<const std::type_info*, void*> components_;
}; // }}}
// {{{ template inlines
template<typename T, typename... Args>
void Entity::addComponent(Args&... args)
{
components_[&typeid(T)] = new T(args...);
}
template<typename T>
T* Entity::getComponent()
{
auto i = components_.find(&typeid(T));
if (i != components_.end())
return static_cast<T*>(i->second);
return nullptr;
}
// }}}
int main() {
Entity e;
e.addComponent<Foo>();
e.addComponent<Bar>();
Foo* foo = e.getComponent<Foo>();
Bar* bar = e.getComponent<Bar>();
foo->dump();
bar->dump();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment