Skip to content

Instantly share code, notes, and snippets.

@eruffaldi
Created November 17, 2015 10:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eruffaldi/05b69afefee58634f180 to your computer and use it in GitHub Desktop.
Save eruffaldi/05b69afefee58634f180 to your computer and use it in GitHub Desktop.
C++ Type Specifier
#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