如何将类型名称T转换为c ++中的字符串 [英] How to convert typename T to string in c++
问题描述
在c ++中使用模板播放时,我遇到了一个问题,将名称T转换为字符串。例如:
template< typename T>
class Matrix {
public:
Matrix(){
// my_type = T的字符串类型,即如果T是char。我想my_type是char。
}
string my_type;
}
如何将T转换为一个字符串, p>
注意:我只是在玩,所以请不要担心什么时候需要这样的东西。
没有内置的机制。 typeid(T):: name()
可以给出一些信息,但是标准不要求这个字符串是人类可读的;只是每种类型不同。 Microsoft Visual C ++使用人类可读的字符串; GCC不会。
但你可以构建自己的系统。例如,基于特征。这样的东西:
//默认实现
template< typename T&
struct TypeName
{
static const char * Get()
{
return typeid(T).name();
}
};
//为你想要支持的每个类型的特殊化
//不喜欢typeid返回的字符串
template<>
struct TypeName< int>
{
static const char * Get()
{
returnint;
}
};
//用法:
const char * name = TypeName< MyType> :: Get();
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;
}
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 mechanizm for this. typeid(T)::name()
can give some info, but the standard does not mandate this string to be human-readable; just distinct for each type. 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();
这篇关于如何将类型名称T转换为c ++中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!