Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
403 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...