I want to be able to create a method in a templated class that returns the name of the type subsituted in the template parameter.
eg:
template <typename T>
class CPropertyValueT
{
std::string GetTypeName()
{
return #T;
}
}
This is possible with a preprocessor macro using #, I figured there must be a way with templates.
Is this possible?
You can use typeid(T).name()
, though it will return decorated name of the type.
If you're using GCC, then you can use GCC API, declared incxxabi.h
header, to demangle the names.
Here is an example (source):
#include <exception>
#include <iostream>
#include <cxxabi.h>
struct empty { };
template <typename T, int N>
struct bar { };
int main()
{
int status;
char *realname;
// exception classes not in <stdexcept>, thrown by the implementation
// instead of the user
std::bad_exception e;
realname = abi::__cxa_demangle(e.what(), 0, 0, &status);
std::cout << e.what() << "\t=> " << realname << "\t: " << status << '\n';
free(realname);
// typeid
bar<empty,17> u;
const std::type_info &ti = typeid(u);
realname = abi::__cxa_demangle(ti.name(), 0, 0, &status);
std::cout << ti.name() << "\t=> " << realname << "\t: " << status << '\n';
free(realname);
return 0;
}
Output:
St13bad_exception => std::bad_exception : 0
3barI5emptyLi17EE => bar<empty, 17> : 0
Another interesting link that describe demangling in GCC and Microsoft VC++:
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