Last active
August 29, 2015 13:56
-
-
Save christianparpart/9190331 to your computer and use it in GitHub Desktop.
clang -std=c++11 -o components-example components-example.cpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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