如何在 C++ 中将 typename T 转换为字符串

2021-12-13 00:00:00 templates c++

在 C++ 中使用模板时,我遇到了将 typename T 转换为字符串的问题.例如:

While playing with templates in c++ I encountered a problem converting typename T to string. For example:

template <typename T>
class Matrix {
   public:
        Matrix() {
           //my_type = string type of T. i.e. if T is char. I want my_type to be "char".
        }
   string my_type;
}

如何将 T 转换为表示 T 是什么的字符串.

How do I convert T to a string that says what T is.

注意:我只是在玩,所以请不要担心什么时候可能需要这样的东西.

Note: I'm just playing around so please do not worry about when one might need such a thing.

推荐答案

没有针对此的内置机制.

There is no built-in mechanism for this.

typeid(T)::name() 可以提供一些信息,但标准并没有要求这个字符串是人类可读的;只是它必须对每种类型都不同.(例如 Microsoft Visual C++ 使用人类可读的字符串;GCC 不使用.)

typeid(T)::name() can give some info, but the standard does not mandate this string to be human-readable; just that it has to be distinct for each type. (E.x. Microsoft Visual C++ uses human-readable strings; GCC does not.)

不过,您可以构建自己的系统.例如,基于特征.像这样:

You can build your own system though. For example, traits-based. Something like this:

// default implementation
template <typename T>
struct TypeName
{
    static const char* Get()
    {
        return typeid(T).name();
    }
};

// a specialization for each type of those you want to support
// and don't like the string returned by typeid
template <>
struct TypeName<int>
{
    static const char* Get()
    {
        return "int";
    }
};

// usage:
const char* name = TypeName<MyType>::Get();

相关文章