How to convert typename T to string in c++(如何在 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 转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 C++ 中将 typename T 转换为字符串
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
