The problem with using typeid(*this).name() is that there is no this pointer in the call to the static method. The __PRETTY_FUNCTION__ macro reports the class name in static functions, as well as method calls. However, this will only work with gcc.
Here is an example of retrieving information through a macro style interface.
inline std::string methodName(const std::string& prettyFunction) { size_t colons = prettyFunction.find("::"); size_t begin = prettyFunction.substr(0,colons).rfind(" ") + 1; size_t end = prettyFunction.rfind("(") - begin; return prettyFunction.substr(begin,end) + "()"; } #define __METHOD_NAME__ methodName(__PRETTY_FUNCTION__)
The __METHOD_NAME__ macro will return the form string <class>::<method>() , truncate the return type, modifiers and arguments from what __PRETTY_FUNCTION__ gives.
For something that only retrieves the class name, care must be taken to avoid situations where there is no class:
inline std::string className(const std::string& prettyFunction) { size_t colons = prettyFunction.find("::"); if (colons == std::string::npos) return "::"; size_t begin = prettyFunction.substr(0,colons).rfind(" ") + 1; size_t end = colons - begin; return prettyFunction.substr(begin,end); } #define __CLASS_NAME__ className(__PRETTY_FUNCTION__)
Andrew Prock Apr 02 '13 at 22:24 2013-04-02 22:24
source share