我希望能够在模板化类中创建一个方法,该方法返回模板参数中替换的类型的名称.
例如:
template <typename T>
class CPropertyValueT
{
std::string GetTypeName()
{
return #T;
}
}
Run Code Online (Sandbox Code Playgroud)
使用#的预处理器宏可以实现这一点,我想必须有一种模板方法.
这可能吗?
您可以使用typeid(T).name(),但它将返回该类型的装饰名称.
如果您正在使用GCC,那么您可以使用cxxabi.h标头中声明的GCC API 来解码名称.
这是一个例子(来源):
#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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
St13bad_exception => std::bad_exception : 0
3barI5emptyLi17EE => bar<empty, 17> : 0
Run Code Online (Sandbox Code Playgroud)
另一个有趣的链接描述了GCC和Microsoft VC++中的demangling: