c++ - 如何在 C++ 中将类型名 T 转换为字符串

标签 c++ templates

在使用 c++ 中的模板时,我遇到了将类型名 T 转换为字符串的问题。例如:

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 是什么的字符串。

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

最佳答案

对此没有内置机制。

typeid(T)::name() 可以提供一些信息,但标准不强制此字符串是人类可读的;只是它必须对每种类型都不同。 (例如,Microsoft Visual C++ 使用人类可读的字符串;GCC 不使用。)

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

// 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();

关于c++ - 如何在 C++ 中将类型名 T 转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4484982/

相关文章:

c++ - 公私钥加密教程

c++ - Qt 链接器错误

c++ - 子类对象作为虚函数的参数

c++ - 编译时模板实例化检查

c++ - 重载函数模板和继承参数

c++ - 与 SFINAE 中的硬错误混淆

c++ - 使用 ifstream::operator>> 从 CSV 文件加载数组

c++ - 使用 iostream << 序列化用户对象

使用 cstrings 的 C++ 段错误

C++ 泛型列表赋值