I have code:
template<class T>
class MyClass{
MyClass(){
std::cout << MY_MACRO(T);
}
};
Is it possible to write such macro that returns type of template argument as a string? If yes, how?
For example,
MyClass<int> ins; // print 'int' to console
As a couple other people have mentioned you could do something with RTTI but I don't think it is quite 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 comment from @MM - if you are using gcc and don't mind making the macro into a function you could use abi::__cxa_demangle
. You need to include 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
You could use overloaded functions for that like
std::string MY_MACRO(int) { return "int"; }
which is used as std::cout << MY_MACRO( T() );
, but you'll need to define such function for every type you use as template parameter.
Or you could use run-time type identification via typeid
function.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.