Something between __func__ and __PRETTY_FUNCTION__?

后端 未结 2 1850
盖世英雄少女心
盖世英雄少女心 2020-12-15 14:31

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

相关标签:
2条回答
  • 2020-12-15 15:12

    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.

    0 讨论(0)
  • 2020-12-15 15:29

    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(...)>
    0 讨论(0)
提交回复
热议问题