Alex Alex - 2 months ago 9
C++ Question

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

This question seems to have been answered before on SO, but despite looking at other solutions I'm still not able to figure out why I am getting the error:


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


I have a class
Runner
which is going to be responsible for scheduling tasks to run any sub-work on separate threads asynchronously.

In the
start
method of my runner I have the following code:

void start(const bool runTaskAsync = true)
{
if(!isRunning()) return;

running = true;

if(runTaskAsync)
{
Worker = std::thread(runTask, this);
}
else
{
this->runTask();
}
}


The troublesome line that the compiler doesn't like is:
Worker = std::thread(runTask, this);
. Based on the error given (and the other questions asked on this site, I attempted to do the following)

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


However I am still getting the same error. The
runTask
method is a private method on the
Runner
class and is defined as:

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()();
}
}
}


The call to
Function()()
calls the template function passed to the
Runner
instance, Runners private member variable of
task
is signed as
std::function<void(void)> task;
and the implementation of
Function()()
is signed as:

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


Which when called (as I understand) will run
Function()
and will then run
task()


If there are any other details required please let me know. I am not currently instantiating any instance of
Runner
, I've simply included
Runner.h
in my
main.cpp
file to see whether it would compile.

Answer

Based on the error given (and the other questions asked on this site, I attempted to do the following)

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

That should be:

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

Every non-static member function takes an implicit this, which is exposed (and required) when you want to pass that member function to std::thread

Comments