Reputation: 1262
I would like to have the following class setup in a program:
I'm having some trouble spawning the std::thread that runs the callback. It seems like I'm getting its parameters wrong, but I can't figure it out.
The minimal reproducible example:
#include <thread>
class MyClass;
class CallbackClass
{
public:
void (MyClass::*callback)();
std::thread a_thread;
void setCallback(void (MyClass::*cb)())
{
callback = cb;
}
void writeCall()
{
a_thread = std::thread(callback); // error here
}
};
class MyClass
{
public:
CallbackClass callbackobject;
MyClass()
{
callbackobject.setCallback(&MyClass::bufferWriter);
}
void bufferWriter(){}
};
int main(){}
The compiler error I get:
error: no matching function for call to ‘std::thread::_Invoker<std::tuple<void (MyClass::*)()> >::_M_invoke(std::thread::_Invoker<std::tuple<void (MyClass::*)()> >::_Indices)’
operator()()
on this line:
a_thread = std::thread(callback); // error here
Upvotes: 0
Views: 594
Reputation: 118350
void (MyClass::*callback)();
This is a pointer to a class method.
a_thread = std::thread(callback);
A class method is not a function that can be called by itself. The class method requires an object for which it gets invoked. You need to store, or obtain a pointer to a MyClass
object, from somewhere. For example, you can pass a 2nd parameter to `setCallback:
void setCallback(void (MyClass::*cb)(), MyClass *ptr)
and then stash it away, somewhere, then use it to invoke the class method. Typically, this would be something like:
a_thread = std::thread(callback, ptr);
Upvotes: 2