Created
November 17, 2015 10:44
-
-
Save eruffaldi/05b69afefee58634f180 to your computer and use it in GitHub Desktop.
C++ Type Specifier
This file contains 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 <typeinfo> | |
#include <functional> | |
#include <iostream> | |
#include <map> | |
struct TypeSpec | |
{ | |
const char * name; // pure name | |
std::function<bool(std::ostream&,void*)> out; // conversion fx | |
const std::type_info & ti; // internal name (unique) | |
TypeSpec(const char * xname,const std::type_info & xti, std::function<bool(std::ostream&,void*)> xout); | |
}; | |
std::map<std::string,TypeSpec *> types; // registry | |
TypeSpec::TypeSpec(const char * xname, const std::type_info & xti, std::function<bool(std::ostream&,void*)> xout): | |
name(xname),out(xout),ti(xti) | |
{ | |
types[ti.name()] = this; | |
} | |
/// lookup at compile time | |
template <class T> | |
TypeSpec * findtype() | |
{ | |
auto it = types.find(typeid(T).name()); | |
if(it != types.end()) | |
return it->second; | |
else | |
return 0; | |
} | |
/// registration | |
#define TYPESPEC(T) \ | |
TypeSpec T##_spec = TypeSpec ( #T, typeid(T), \ | |
[] (std::ostream & ons, void * p) -> bool { \ | |
ons << *(T*)p;\ | |
return (bool)ons;\ | |
} \ | |
); | |
TYPESPEC(int); | |
TYPESPEC(float); | |
int main(int argc, char * argv[]) | |
{ | |
for(auto & t : types) | |
{ | |
std::cout << t.first << " " << t.second->name << std::endl; | |
} | |
int w = 10; | |
findtype<int>()->out(std::cout,&w); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment