在c++中使用模板时,我遇到了将typename转换为字符串的问题。例如:
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是什么的字符串。
注意:我只是随便玩玩,所以请不要担心什么时候会需要这样的东西。
发布于 2010-12-20 04:57:52
这方面没有内置的机制。
typeid(T)::name()可以提供一些信息,但标准并没有要求这个字符串必须是人类可读的;只是对于每种类型,它必须是不同的。(E.x。( 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();发布于 2010-12-20 06:46:54
对GCC来说,你必须使用一个技巧。使用cxxabi.h,我为此编写了一个小包装器:
#include <string>
#include <iostream>
#include <iomanip>
#include <typeinfo>
#include <cxxabi.h>
#define DEBUG_TYPE(x) do { typedef void(*T)x; debug_type<T>(T(), #x); } while(0)
template<typename T>
struct debug_type
{
template<typename U>
debug_type(void(*)(U), const std::string& p_str)
{
std::string str(p_str.begin() + 1, p_str.end() - 1);
std::cout << str << " => ";
char * name = 0;
int status;
name = abi::__cxa_demangle(typeid(U).name(), 0, 0, &status);
if (name != 0) { std::cout << name << std::endl; }
else { std::cout << typeid(U).name() << std::endl; }
free(name);
}
};双括号是必要的。适用于任何类型。
现在,您可以将其用于boost::mpl
DEBUG_TYPE((if_c<true, true_, false_>::type));将打印:
if_c<true, true_, false_>::type => bool_<true>发布于 2010-12-20 04:44:49
你不能,至少不能直接这么做。将一个或一系列标记转换为字符串文字的唯一方法是在宏内使用预处理器的字符串化运算符(#)。
如果想要获得表示类型的字符串文字,则必须自己编写一些内容,可能是使用宏来实例化模板并将字符串类型名称传递给它。
任何通用方法的一个问题是:应该为以下用途提供什么字符串:
Matrix<char> x;
typedef char MyChar;
Matrix<MyChar> y;x和y都属于同一类型,但一个直接使用char,另一个使用类型定义MyChar。
https://stackoverflow.com/questions/4484982
复制相似问题