Created
December 13, 2016 20:50
-
-
Save Porges/aaafbaff1460d8e2c7e4a6971864cf41 to your computer and use it in GitHub Desktop.
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 <iostream> | |
#include <string> | |
#include <typeindex> | |
#include <typeinfo> | |
#include <unordered_map> | |
// We want to put all registered types into a map: | |
std::unordered_map<std::type_index, std::string> registered_types; | |
template<class T> | |
struct register_me | |
{ | |
register_me() | |
{ | |
// do whatever is needed here... | |
registered_types[std::type_index(typeid(T))] = typeid(T).name(); | |
} | |
}; | |
// Base type: | |
template<class T> | |
struct base | |
{ | |
const static register_me<T> on_init; | |
base() | |
{ | |
// make sure it's actually referenced somewhere so it gets instantiated | |
// (but there's no runtime cost in the constructor) | |
on_init; | |
} | |
}; | |
template<class T> | |
const register_me<T> base<T>::on_init; | |
// Derivees: | |
class foo : base<foo> | |
{}; | |
class bar : base<bar> | |
{}; | |
int main() | |
{ | |
foo f; | |
std::cout << registered_types.size() << '\n'; | |
for (const auto& types : registered_types) | |
{ | |
std::cout << types.second << '\n'; | |
} | |
// bar b; | |
// if unused, it won't show up, but it doesn't matter where it's used, | |
// it will always be registered | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment