Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ template black magic

Tags:

c++

templates

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!

like image 290
anon Avatar asked Nov 28 '22 19:11

anon


1 Answers

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.

like image 102
sth Avatar answered Dec 11 '22 00:12

sth