Skip to content

Instantly share code, notes, and snippets.

@christianparpart
Last active August 29, 2015 13:56
Show Gist options
  • Save christianparpart/9190331 to your computer and use it in GitHub Desktop.
Save christianparpart/9190331 to your computer and use it in GitHub Desktop.
clang -std=c++11 -o components-example components-example.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) {
components_[&typeid(T)] = new T(args...);
}
template<typename T>
T* getComponent() {
auto i = components_.find(&typeid(T));
if (i != components_.end())
return static_cast<T*>(i->second);
return nullptr;
}
private:
std::unordered_map<const std::type_info*, void*> components_;
}; // }}}
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