介于__func_和__PRETY_FUNCTION_之间

Something between __func__ and __PRETTY_FUNCTION__?

本文关键字:FUNCTION 之间 PRETY func 介于      更新时间:2023-10-16

我使用g++4.8.1,并使用这两个宏进行调试。但是,__func__宏只给了我函数名,如果在不同的类中有许多同名函数,这可能会产生误导。__PRETTY_FUNCTION__宏生成整个函数签名,包括返回类型、类名和所有参数,这些参数可能很长。

我想要一个介于两者之间的宏,它只给我类名和函数名。有什么办法做到这一点吗?

受此启发,我创建了以下宏__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) + "(...)");
}

它的作用:

  • 需要__PRETTY_FUNCTION__
  • 它删除返回类型和所有参数
  • 如果函数的参数为零,则会附加(),否则为(...)

特点:

  • 处理命名空间、构造函数等
  • 也适用于括号运算符

限制:

  • 它只适用于gcc
  • 在运行时而非编译时创建
  • 已分配堆
  • 不适用于Lambda,__FUNCTION____PRETTY_FUNCTION__不匹配。。。我几乎可以称之为编译器错误:)
    • __FUNCTION__看到operator()
    • __PRETTY_FUNCTION__<lambda(...)>

不幸的是,我认为这不容易做到。我不明白为什么从来没有人提出实现__CLASS__宏,它可以扩展到当前类,例如,类似于GCC定义的所有宏。

我同意这些宏在一些困难的调试情况下是很有帮助的。可能难以实施。