__func__ 和 __PRETTY_FUNCTION__ 之间的东西?

HEK*_*KTO 6 c++ macros gcc

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

我想要一些东西 - 一个宏,它只会给我类名和函数名。有什么方法可以实现吗?

Ant*_*nio 7

灵感来自这个,我创建了下面的宏__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) + "(...)");
}
Run Code Online (Sandbox Code Playgroud)

它能做什么:

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

特征:

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

限制:

  • 它只适用于 gcc
  • 在运行时创建而不是编译时
  • 堆分配。
  • 不适用于 lambda,__FUNCTION__并且__PRETTY_FUNCTION__不匹配......我几乎将其称为编译器错误 :)
    • __FUNCTION__ 看到一个 operator()
    • __PRETTY_FUNCTION__ 看到 <lambda(...)>

  • 限制:在运行时创建而不是在编译时创建,并且是堆分配的。 (2认同)