C++ 在代码中获取字符串形式的类名
#include <iostream> #include <string> #include <typeinfo> #include <cxxabi.h> template <typename T> class TypeTraits { public: static std::string Name() { const char* name = typeid(T).name(); std::string ret; int status = 0; char *demangled = abi::__cxa_demangle(name, 0, 0, &status); if (status == 0) { ret = std::string(demangled); std::free(demangled); } else { ret = std::string(name); } return ret; } }; template <typename T> class A { }; int main() { static std::string name = TypeTraits<A<int>>::Name(); std::cout << name << std::endl; // output: A<int> return 0; }