This only needs to work in g ++.
I need a function
template<typename T> std::string magic();
such that:
Class Foo{}; magic<Foo>(); // returns "Foo"; Class Bar{}; magic<Bar>(); // returns "Bar";
I donβt want this to be done using specialization (i.e. to define magic for each type. I hope to get the macro / template black magic here. Does anyone know how?)
Thank!
Try typeid(Foo).name()to get started. Disassemble as you see fit; will be implementation dependent (but just wrapping the line is wrapped back).
typeid(Foo).name()
( ) , , , . , ββ :
template<typename T> std::string magic_impl(const char *name) { return name; } #define more_magic(a) magic_impl<a>(#a) #define magic(a) more_magic(a)
magic(int) "int", magic(Foo) "Foo was not announce", .
magic(int)
"int"
magic(Foo)
, :
#define MAGICCLASSNAME(str) std::string magic(#str) class Foo{}; MAGICCLASSNAME(foo)
:
#include <iostream> #include <string> #include <typeinfo> using namespace std; class Foo{}; class Bar{}; template<typename T> inline std::string magic(const T& obj) { return typeid(obj).name(); } int main() { Foo a; cout << magic<Foo>(a); // returns "Foo"; }
g++ .
SO.
++, , . , Modern ++ Design .