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