Type argument to string

I have a code:

template<class T> class MyClass{ MyClass(){ std::cout << MY_MACRO(T); } }; 

Is it possible to write a macro that returns the type of the template argument as a string? If so, how?

For instance,

 MyClass<int> ins; // print 'int' to console 
+4
source share
2 answers

As a couple of other people mentioned that you can do something with RTTI, but I don’t think this is exactly what you are looking for:

 #include <typeinfo> #include <iostream> #include <string> #define MY_MACRO(obj) typeid(obj).name() template<class T> class MyClass { public: MyClass(){ T b; std::cout << MY_MACRO(b) << std::endl; } }; class TestClass {}; int main(int argc, char** argv) { MyClass<std::string> a; MyClass<int> b; MyClass<TestClass> c; return 0; } 

Outputs:

 Ss i 9TestClass 

Thanks to a comment from @MM - if you use gcc and don't mind turning a macro into a function, you can use abi::__cxa_demangle . You need to enable cxxabi.h

 size_t size; int status; std::cout << abi::__cxa_demangle(typeid(obj).name(), NULL, &size, &status) << std::endl; 

Output:

 std::string int TestClass 
+2
source

You can use overloaded functions for such as

 std::string MY_MACRO(int) { return "int"; } 

which is used as std::cout << MY_MACRO( T() ); , but you need to define such a function for each type that you use as a template parameter.

Or you can use runtime type identification using the typeid function.

+1
source

All Articles