简体   繁体   English

获取调用函数的类的名称

[英]Get the name of the class calling a function

Context 上下文

I'm writting a debug class in Qt for a project and I want to know in which class I am so now I write: 我正在Qt中为一个项目编写一个调试类,我想知道我在哪个类中,所以我写:

MyClass::function1()
{
   DEBUG_IN("[MyClass] Enters function1()")
   ....do something
   DEBUG_OUT("[MyClass] Exits function1()");
}

EDIT: DEBUG_IN() and DEBUG_OUT() are global functions. 编辑: DEBUG_IN()DEBUG_OUT()是全局函数。 They are not part of the class MyClass 它们不属于MyClass类

The question 问题

Is it possible to get the name of the class where DEBUG() is called? 是否可以获取调用DEBUG()的类的名称?

(and the bame of the function where DEBUG() is called?) (以及调用DEBUG()的函数的作用?)

so that I could just do: 这样我就可以做到:

MyClass::function1()
{
   DEBUG_IN("function1()")
   ....do something
   DEBUG_OUT("function1()");
}

and

DEBUG_IN(QString text)
{
   qDebug() << qPrintable("[")
            << qPrintable(getClassName())
            << qPrintable("] Enters ")
            << qPrintable(text);
}

Thx a lot 多谢

The closest to what you want would be __PRETTY_FUNCTION__ . 最接近您想要的是__PRETTY_FUNCTION__ This includes fully qualified function name and signature. 这包括标准功能名称和签名。

Edit: 编辑:

You should use it like this: 您应该这样使用它:

#define DEBUG_IN_PRETTY(...) DEBUG_IN(__PRETTY_FUNCTION__, __VA_ARGS__)

then call DEBUG_IN_PRETTY (obviously DEBUG_IN needs to take the extra argument). 然后调用DEBUG_IN_PRETTY (显然DEBUG_IN需要使用额外的参数)。 This will expand the macro at the call site. 这将在呼叫站点扩展宏。

Indeed there is. 确实有。

typeid(*this).name()

Will give you a readable classname. 将为您提供可读的类名。 It is not specified how this name is constructed so your compiler might not give the exact class name, but it should be good for debugging purposes. 没有指定此名称的构造方式,因此您的编译器可能不会提供确切的类名称,但对于调试目的应该是很好的。

As DEBUG_IN and DEBUG_OUT are free functions you need to pass the class type as an argument. 由于DEBUG_IN和DEBUG_OUT是自由函数,因此您需要将类类型作为参数传递。 A simple template should do the trick 一个简单的模板应该可以解决问题

template<typename CLASSNAME>
void DEBUG_IN(QString msg, CLASSNAME* that)
{
   ...  typeid(*that).name()

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM