不,它也不能与 typeid 一起工作。它将为您提供一些取决于编译器实现的内部字符串。像“int”这样的东西,但“i”也很常见int
。
顺便说一句,如果您只想比较两种类型是否相同,则无需先将它们转换为字符串。你可以做
template<typename A, typename B>
struct is_same { enum { value = false }; };
template<typename A>
struct is_same<A, A> { enum { value = true }; };
然后做
if(is_same<T, U>::value) { ... }
Boost 已经有了这样的模板,下一个 C++ 标准也会有std::is_same
。
手动注册类型
您可以专注于以下类型:
template<typename>
struct to_string {
// optionally, add other information, like the size
// of the string.
static char const* value() { return "unknown"; }
};
#define DEF_TYPE(X) \
template<> struct to_string<X> { \
static char const* value() { return #X; } \
}
DEF_TYPE(int); DEF_TYPE(bool); DEF_TYPE(char); ...
所以,你可以像这样使用它
char const *s = to_string<T>::value();
当然,如果你想在类型未知的情况下获得编译时错误,你也可以去掉主模板定义(只保留前向声明)。我只是将其包含在此处以完成。
我以前使用过 char const* 的静态数据成员,但它们会导致一些复杂的问题,例如在何处放置它们的声明等问题。像上面这样的类专业化很容易解决这个问题。
自动,取决于 GCC
另一种方法是依赖编译器内部。在 GCC 中,以下给出了合理的结果:
template<typename T>
std::string print_T() {
return __PRETTY_FUNCTION__;
}
归来std::string
。
std::string print_T() [with T = std::basic_string<char, std::char_traits<char>, std::allocator<char> >]
一些substr
混合的魔法find
会给你你寻找的字符串表示。