出于调试目的(在c ++ 11模式下使用g ++ 4.6的Linux平台上)我想知道模板实例化的确切类型。之前讨论过类似的事情:Print template typename at compile time和How to convert typename T to string in c++,但我对解决方案并不满意。我想出了以下代码:
#include <typeinfo>
#include <type_traits>
#include <string>
template<typename FIRST> std::string typeName() {
std::string tName;
// get name of the type (and remove the '\n' at the end)
FILE *fp = popen((std::string("c++filt -t ") + std::string(typeid(FIRST).name())).c_str(), "r");
char buf[1024]; fgets(buf, 1024, fp); fclose(fp);
tName += buf; tName.erase(std::prev(tName.end()));
// check whether we have a const qualifier
if(std::is_const<FIRST>::value) { tName += " const"; }
// check whether type declares a volatile variable
if(std::is_volatile<FIRST>::value) { tName += " volatile"; }
// check for lvalue and rvalue references
if(std::is_lvalue_reference<FIRST>::value) { tName += "&"; }
if(std::is_rvalue_reference<FIRST>::value) { tName += "&&"; }
return tName;
}
template<typename FIRST, typename SECOND, typename... OTHER> std::string typeName() {
return typeName<FIRST>() + ", " + typeName<SECOND, OTHER...>();
}
#include <iostream>
int main() {
std::cout << typeName<std::string*&, int&&, char const* const>() << std::endl;
return 0;
}
由
编译时g++ -std=gnu++0x -o test test.cpp
打印
std::basic_string<char, std::char_traits<char>, std::allocator<char> >*&, int&&, char const* const
基本上我对输出很满意,但是我通过调用c ++ filt得到demangeled typename的方式非常糟糕。你看到另一种方法来实现相同的输出吗?
感谢您的任何提示!