This needs only work in g++.
I want 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 via specialization (i.e. having to define magic for each type. I'm hoping to pull some macro/template black magic here. Anyone know how?)
Thanks!
To convert a type (or other identifer) into a string you need a macro, but a macro can not check if it's parameter is a valid type. To add type checking a template function can be added to the macro:
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)
Here magic(int)
gives the string "int"
while magic(Foo)
gives a "‘Foo’ was not declared" error if there is no such class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With