【问题标题】:Callback function in QThread ClassQThread类中的回调函数
【发布时间】:2019-05-12 20:06:47
【问题描述】:

我有一个基于 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&lt;void (int, std::string, int)&gt;' (aka 'const function&lt;void (int, basic_string&lt;char&gt;, int)&gt;') could not bind to an rvalue of type 'void (MyClass::*)(int, std::string, int)'

【问题讨论】:

  • “最后错过了什么”是什么意思?你试过void f(int, std::string, int) {}吗?
  • 如何将这个 f 传递给 SomFunc? @nwp
  • SomFunc(f);。不过,这似乎是一个棘手的问题。
  • 错误:引用类型 'const std::function' (又名 'const function, int) >') 无法绑定到 'void (MyClass::*)(int, std::string, int)' @nwp 类型的右值
  • 你必须捕获你想要访问的东西。 [variable] 进行复制,[&amp;variable] 捕获引用(确保在调用函数时引用的变量没有死亡)。您可能需要执行[this] 来捕获可让您访问所有 MainWindow 内容的窗口。您可以使用[variable, this, &amp;other_variable] 捕获多个内容。

标签: c++ qt std-function


【解决方案1】:

你可以这样做:

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

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-24
    • 1970-01-01
    • 1970-01-01
    • 2020-11-12
    • 2020-12-05
    • 1970-01-01
    • 2014-09-26
    • 1970-01-01
    相关资源
    最近更新 更多