且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C++ 获取模板中的类型名称

更新时间:2021-09-02 05:53:05

Jesse Beder 的解决方案可能是***的,但是如果你不喜欢 typeid 给你的名字(我认为 gcc 给你的名字是混乱的),你可以执行以下操作:

Jesse Beder's solution is likely the best, but if you don't like the names typeid gives you (I think gcc gives you mangled names for instance), you can do something like:

template<typename T>
struct TypeParseTraits;

#define REGISTER_PARSE_TYPE(X) template <> struct TypeParseTraits<X> 
    { static const char* name; } ; const char* TypeParseTraits<X>::name = #X


REGISTER_PARSE_TYPE(int);
REGISTER_PARSE_TYPE(double);
REGISTER_PARSE_TYPE(FooClass);
// etc...

然后像这样使用

throw ParseError(TypeParseTraits<T>::name);

您也可以将两者结合起来,将 name 更改为默认调用 typeid(T).name() 的函数,然后只针对以下情况这是不可接受的.

You could also combine the two, change name to be a function that by default calls typeid(T).name() and then only specialize for those cases where that's not acceptable.