__func__ 和 __PRETTY_FUNCTION__ 之间的东西?

2022-01-11 00:00:00 gcc macros c++

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

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?

推荐答案

灵感来自 这个,我创建了如下宏__COMPACT_PRETTY_FUNCTION__:

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) + "(...)");
}

它的作用:

  • 需要 __PRETTY_FUNCTION__
  • 它删除了返回类型和所有参数
  • 如果函数的参数为??零,则附加 (),否则附加 (...)
  • It takes __PRETTY_FUNCTION__
  • It removes return type and all arguments
  • If the function has zero arguments, it appends (), otherwise (...)

特点:

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

限制:

  • 它只适用于 gcc
  • 在运行时而不是编译时创建
  • 已分配堆.
  • 不适用于 lambda,__FUNCTION____PRETTY_FUNCTION__ 不不匹配 ...我几乎称它为编译器错误:)
    • __FUNCTION__ 看到 operator()
    • __PRETTY_FUNCTION__ 看到 <lambda(...)>
    • 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(...)>

相关文章