开发者

Get type name as string in Visual Studio 2010

开发者 https://www.devze.com 2023-02-09 10:02 出处:网络
How can I get the type name of a supplied type as string with C++ using Visual Studio 2010? Example: class MyClass { ... };

How can I get the type name of a supplied type as string with C++ using Visual Studio 2010?

Example:

class MyClass { ... };

std::string typestr;
typestr = typeof( MyClass );

//ty开发者_如何学Gopestr should hold "MyClass" now


typeid(type).name();
//Or
typeid(expression).name();

Will return type name. This feature is "implementation defined" and standard doesn't saying what exacly name function must return, however in VC++ it is returning what you need (note, that in g++ name function have different behavior).

For more information see this and this links.


Either use a macro like @badgerr says, if you can deduce it at compile-time. If you need it at runtime, then you need to enable RTTI (run-time type information) and use the typeid operator, which returns a const type_info& object, which has a name method. You can use it either with an expression or with a typename.

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;
    }   
}

More on typeid.


typeid may be what you need.

Or you could use some ugly define hacks:

//# is the Stringizing operator
#define typeof(X) #X

See here for docs/warnings: http://msdn.microsoft.com/en-us/library/7e3a913x%28v=VS.100%29.aspx

0

精彩评论

暂无评论...
验证码 换一张
取 消