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 转换为字符串
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- C++ 协变模板 2021-01-01
- 静态初始化顺序失败 2022-01-01
