如何在 C++ 中将 typename T 转换为字符串 [英] How to convert typename T to string in c++

查看:45
本文介绍了如何在 C++ 中将 typename T 转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于如何在 C++ 中将 typename T 转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆