QThread类中的回调函数

时间:2019-05-12 20:06:48

标签: c++ qt std-function

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

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

我想在像MyThread :: Callback之类的类中创建一个回调函数,并在上面的函数中调用,并将MyThread :: Callback函数作为实际的回调函数传递。无论我尝试什么,最后都会错过一些东西,我真的对std :: function感到困惑,需要帮助。如何定义一个函数,可以将其作为参数传递给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)'

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

#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 ++中显式使用指针语法。

希望它可以提供帮助。