C++函数调用缺少参数列表;使用 '&Runner::runTask' 创建指向成员的指针

C++ function call missing argument list; use '&Runner::runTask' to create a pointer to member

本文关键字:创建 成员 指针 runTask 函数调用 列表 使用 Runner C++ 参数      更新时间:2023-10-16

这个问题似乎在SO之前已经回答了,但是尽管看了其他解决方案,我仍然无法弄清楚为什么我得到错误:

函数调用缺少参数列表;使用'&Runner::runTask'创建指向成员

的指针

我有一个类Runner,它将负责调度任务,以异步地在单独的线程上运行任何子工作。

在我的跑步者的start方法中,我有以下代码:

void start(const bool runTaskAsync = true)
{
    if(!isRunning()) return;
    running = true;
    if(runTaskAsync)
    {
        Worker = std::thread(runTask, this);
    } 
    else 
    {
        this->runTask();
    }
}

编译器不喜欢的麻烦行是:Worker = std::thread(runTask, this);。根据给出的错误(以及本网站提出的其他问题),我尝试做以下操作

Worker = std::thread(&Runner::runTask);

然而,我仍然得到相同的错误。runTask方法是Runner类上的私有方法,定义为:

void runTask()
{
    while(isRunning())
    {
        // this_thread refers to the thread which created the timer
        std::this_thread::sleep_for(interval);
        if(isRunning())
        {
            // Function is a public method that we need to call, uses double parens because first calls the function called Function
            // and then the second set of parens calls the function that the calling Function returns
            Function()();
        }
    }
}

Function()()的调用调用传递给Runner实例的模板函数,task的runner私有成员变量签名为std::function<void(void)> task;, Function()()的实现签名为:

const std::function<void(void)> &Function() const 
{
    return task;
}

调用时(据我所知)将运行Function(),然后运行task()

如果还需要其他细节,请让我知道。我目前没有实例化Runner的任何实例,我只是将Runner.h包含在我的main.cpp文件中,看看它是否会编译。

根据给出的错误(以及本网站提出的其他问题),我试图做以下事情)

Worker = std::thread(&Runner::runTask);

应该是:

 Worker = std::thread(&Runner::runTask, this);

每个非静态成员函数都接受一个隐式的this,当您想将该成员函数传递给std::thread时,它是公开的(并且是必需的)

这应该能奏效:

Worker = std::thread(&Runner::runTask, this);