Retrieving a c++ class name programmatically

2019-01-13 03:13发布

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.

标签: c++ class macros
3条回答
放我归山
2楼-- · 2019-01-13 03:37

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).

查看更多
Emotional °昔
3楼-- · 2019-01-13 03:41

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.

查看更多
爷的心禁止访问
4楼-- · 2019-01-13 03:53

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.

查看更多
登录 后发表回答