Retrieving a c++ class name programmatically

2019-01-13 03:31发布

问题:

I was wondering if it is possible in C++ to retrieve the name of a class in string form without having to hardcode it into a variable or a getter. I'm aware that none of that information is actually used at runtime, therefor it is unavailable, but are there any macros that can be made to create this functionality?

Edit: May be helpful to note that I'm actually trying to retrieve the name of a derived class, and I'm using Visual C++ 2008 Express Edition.

回答1:

You can use typeid:

#include <typeinfo>
cout << typeid(obj).name() << endl;

However, this is discouraged since the format isn't standardized and may differ between different compilers (or even different versions of the same compiler).



回答2:

If you just want to check if it's certain class, then

typeid(obj) == typeid(CSubClass)

will always work regardless of the implementations.

Otherwise, a convenient way is to declare:

virtual const char* classname() { return "CMyClass";}

and implement per subclass.



回答3:

The typeid(obj).name() thing always gives the type of the variable as it was declared, not the actual type (class) of the object. If the variable obj is assigned to an instance of a subclass of the class that obj was declared as, typeid doesn't reveal that, unfortunately.



标签: c++ class macros