【问题标题】:problem with passing argument to QThreadPool::globalInstance()->start()将参数传递给 QThreadPool::globalInstance()->start() 的问题
【发布时间】:2020-12-25 03:14:31
【问题描述】:

所以我在 AntiFlood 类中有这个成员函数:

void AntiFlood::unBan()
{
    QThread::msleep(5000);
    std::string lineToPost = "KICK " + roomToPost +" "+ nickToPost + "\r\n";
    sendIT(lineToPost);
}
 

我想将它传递给: threadpool.globalInstance()->start(unBan);

  • 这不起作用 - 结果错误:没有匹配的函数调用 'QThreadPool::start()' threadpool.globalInstance()->start(unBan); ^; 但另一方面,如果我使用 lambda:

      auto lam = [this, room, nick](){
          QThread::msleep(5000);
          std::string lineToPost = "KICK " + roomToPost +" "+ nickToPost + "\r\n";
          sendIT(lineToPost);
      };
      threadpool.globalInstance()->start(lam);
    

它工作正常。 我如何将 void AntiFlood::unBan() 传递给需要 std::function functionToRun 的 threadpool.globalInstance()->start()?

【问题讨论】:

    标签: c++ qt qthread


    【解决方案1】:

    您看到的基本问题是AntiFlood::unBan 是(或至少“似乎是”)一个非静态成员函数。在这种情况下,必须针对AntiFlood 类型的有效对象调用它。因为QThreadPool::start有签名...

    void QThreadPool::start(std::function<void ()> functionToRun, int priority = 0)
    

    您需要将其传递给“自包含”std::function&lt;void()&gt;,这正是您所做的......

    auto lam = [this, room, nick]()
      {
        QThread::msleep(5000);
        std::string lineToPost = "KICK " + roomToPost +" "+ nickToPost + "\r\n";
        sendIT(lineToPost);
      };
    threadpool.globalInstance()->start(lam);
    

    通过在 lambda 中捕获 this

    简而言之,我想说的是,您目前做事的方式正确/被接受的方式。

    【讨论】:

      猜你喜欢
      • 2020-02-08
      • 2013-01-17
      • 2017-10-08
      • 2016-07-02
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      • 2011-05-08
      • 1970-01-01
      相关资源
      最近更新 更多