Dragon Dragon - 2 months ago 12
C++ Question

Passing class's member function to std::thread

I have a problem with using std::thread in my code:

Class Timer
{
...
public:
void Start(bool Asynch = true)
{
if (IsAlive())
{
return;
}
alive = true;
repeat_count = call_number;
if (Asynch)
{
t_thread = std::thread(&ThreadFunc, this);
}
else
{
this->ThreadFunc();
}
}
void Stop()
{
alive = false;
t_thread.join();
}
...
}


I get following error:


error C2276: '&': illegal operation on bound member function expression


t_thread is class's private std::thread instance, ThreadFunc() is private member function of the class that returns void;

I think I understand that there are 2 ways to send member function to std::thread, if the function is static I would use t_thread = std::thread(threadfunc); But I don't want ThreadFunc to be static, and doing it like this gives me error.

I think I solved the problem by creating another function:

std::thread ThreadReturner()
{
return std::thread([=] { ThreadFunc(); });
}
...
t_thread = ThreadReturner();


This way I don't get errors, but I don't understand why first one doesn't work.

Any help is appreciated.

My question looks like a duplicate, but there's only 1 difference, in the other question's answer, std::thread was used outside of the class declaration or implementation, it was in main(), in which case specifying scope made sense to me, but not when std::thread was called inside of the class. That's the only difference that I saw and why I made this thread, sorry about possible duplicate.

Answer

You should specify the scope

&Timer::ThreadFunc