人类可读的type_info.name() [英] human-readable type_info.name()
本文介绍了人类可读的type_info.name()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经用 g ++
编译了下面的代码,并得到了在注释中写的输出。
I've compiled the following code with g++
, and got output, which written in comments.
template<class T>
void foo(T t) { cout << typeid(t).name() << endl; }
int main() {
foo("f"); //emits "PKc"
foo(string()); //emits "Ss"
}
我知道, type_info.name()
不是标准化的,但是有任何方法可以获得人类可读的结果吗?
I know, that type_info.name()
isn't standartized, but is there any way to get human-readable results?
good enought
Something like the following would be good enought
const char *
class string
推荐答案
您可以使用 abi :: __ cxa_demangle (demangle函数取自这里),只记得调用者负责释放返回:
You can use abi::__cxa_demangle for that (demangle function taken from here), just remember that the caller is responsible for freeing the return:
#include <cxxabi.h>
#include <typeinfo>
#include <iostream>
#include <string>
#include <memory>
#include <cstdlib>
std::string demangle(const char* mangled)
{
int status;
std::unique_ptr<char[], void (*)(void*)> result(
abi::__cxa_demangle(mangled, 0, 0, &status), std::free);
return result.get() ? std::string(result.get()) : "error occurred";
}
template<class T>
void foo(T t) { std::cout << demangle(typeid(t).name()) << std::endl; }
int main() {
foo("f"); //char const*
foo(std::string()); //std::string
}
ideone 。
这篇关于人类可读的type_info.name()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文