Qthread类中的回调功能

Callback function in QThread Class

本文关键字:回调 功能 Qthread      更新时间:2023-10-16

我有一个基于qthread的类,基本上是GUI线程。在此线程中,我使用的另一个具有此函数类型定义的类:

void SomFunc(const std::function<void (int, std::string, int)> &data)

我想在我的课堂中创建一个回调函数,例如myThread ::回调并在上面调用函数,并将我的myThread ::回调函数作为实际回调函数传递。无论我尝试什么,我都会想念一些东西,我真的很困惑的是std ::功能函数,需要帮助。我如何定义一个可以将其作为参数传递给SomFunc的函数,并在我的MyThread类上下文中获取正确的回调

如果我只是创建一个void函数,这就是我得到的:

error: reference to type 'const std::function<void (int, std::string, int)>' (aka 'const function<void (int, basic_string<char>, int)>') could not bind to an rvalue of type 'void (MyClass::*)(int, std::string, int)'

您可以按以下方式执行:

#include <iostream>
#include <string>
void f(int a, std::string b, int c)
{
    std::cout << a << " -- " << b << " -- " << c << std::endl;
}
void someFunc(void (inner)(int, std::string, int), int a, std::string b, int c)
{
    inner(a, b, c);
}
int main()
{
    int a = 5;
    std::string b("text");
    int c = 10;
    someFunc(f, a, b, c);
    return 0;
}

也可以明确传递指针或参考:

void someFunc(void (*inner)(int, std::string, int), int a, std::string b, int c)
// OR
void someFunc(void (&inner)(int, std::string, int), int a, std::string b, int c)

如果使用指针语法,则可以通过:

替换呼叫
someFunc(&f, a, b, c);

但是,无论如何,编译器都会通过指针静静地替换您的语法选择,因此您无需明确使用C 中的指针语法。

希望它能有所帮助。