如何使用Visual Studio 2010将提供的类型的类型名称作为字符串用C ++获取?
示例:
class MyClass { ... };
std::string typestr;
typestr = typeof( MyClass );
//typestr should hold "MyClass" now
答案 0 :(得分:3)
typeid(type).name();
//Or
typeid(expression).name();
将返回类型名称。这个特性是“实现定义的”,标准没有说明什么是exacly name函数必须返回,但是在VC ++中它返回你需要的东西(注意,g ++名称函数中的有不同的行为)。
答案 1 :(得分:2)
要么像@badgerr那样使用宏,如果你可以在编译时推断它。如果在运行时需要它,则需要启用RTTI(运行时类型信息)并使用typeid
运算符,该运算符返回const type_info&
对象,该对象具有name
方法。您可以将它与表达式或类型名一起使用。
class myClass{
// ...
};
int main(void){
myClass myObject;
cout << "typeid(myObject).name() = " << typeid(myObject).name() << endl;
if (typeid(myObject) == typeid(myClass) {
cout << "It's the same type as myClass" << endl;
}
}
答案 2 :(得分:1)
typeid可能就是您所需要的。
或者你可以使用一些丑陋的定义黑客:
//# is the Stringizing operator
#define typeof(X) #X
请参阅此处了解文档/警告:http://msdn.microsoft.com/en-us/library/7e3a913x%28v=VS.100%29.aspx