I work with g++ 4.8.1 and use these two macros for debugging. However, the __func__
macro gives me only the function name, which might be misleading in the case you have many functions with the same name in different classes. The __PRETTY_FUNCTION__
macro produces the whole function signature - with return type, class name and all arguments, which can be very long.
I'd like to have something between - a macro, which will give me only class name and function name. Any way to achieve that?
Inspired by this, I created the following macro __COMPACT_PRETTY_FUNCTION__
:
std::string computeMethodName(const std::string& function, const std::string& prettyFunction);
#define __COMPACT_PRETTY_FUNCTION__ computeMethodName(__FUNCTION__,__PRETTY_FUNCTION__).c_str() //c_str() is optional
std::string computeMethodName(const std::string& function, const std::string& prettyFunction) {
size_t locFunName = prettyFunction.find(function); //If the input is a constructor, it gets the beginning of the class name, not of the method. That's why later on we have to search for the first parenthesys
size_t begin = prettyFunction.rfind(" ",locFunName) + 1;
size_t end = prettyFunction.find("(",locFunName + function.length()); //Adding function.length() make this faster and also allows to handle operator parenthesys!
if (prettyFunction[end + 1] == ')')
return (prettyFunction.substr(begin,end - begin) + "()");
else
return (prettyFunction.substr(begin,end - begin) + "(...)");
}
What it does:
- It takes
__PRETTY_FUNCTION__
- It removes return type and all arguments
- If the function has zero arguments, it appends
()
, otherwise (...)
Features:
- Handles namespaces, constructors and so on
- Works also with the parenthesis operator!
Limitations:
- It only works with gcc
- Created at runtime rather than compile time
- Heap allocated.
- Does not work for lambdas,
__FUNCTION__
and __PRETTY_FUNCTION__
don't match... I would almost call it a compiler bug :)
__FUNCTION__
sees an operator()
__PRETTY_FUNCTION__
sees <lambda(...)>
Unfortunatly, I don't think this can be done easily. I am one of those that don't understand why nobody ever proposed the implementation of a __CLASS__
macro, that could expand to the current class, similarly to all the macros defined by GCC, for example.
I agree that these macros are great help in some difficult debugging situations. Probably difficult to implement.