使用std :: function作为参数通过std :: thread调用可调用对象

时间:2018-11-10 09:24:20

标签: c++

我正在尝试创建对成员函数的异步调用,该成员函数作为std :: function类型参数获取。但是,出现以下错误:

Error   C2672   'std::invoke': no matching overloaded function found
Error   C2893   Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...) noexcept(<expr>)'   

代码看起来像这样

void clientMessageHandler(MyBaseObject * objectBase, char * buffer, size_t size)
{

}

   void MyObject::dispatcher(std::function<void(MyBaseObject *, char *, size_t)> pfnMessageHandler)
        {
        }

void MyObject::recv(std::function<void(MyBaseObject *, char *, size_t)> pfnMessageHandler)
{
    m_dispatchThread = std::thread(&MyObject::dispatcher, pfnMessageHandler);
}

主要:

MyObject object;
object.recv(clientMessageHandler);

1 个答案:

答案 0 :(得分:1)

MyObject::dispatcherstatic成员函数吗?否则,您需要提供一个对象,以使用std::thread对其进行调用:

m_dispatchThread = std::thread(&MyObject::dispatcher, this, pfnMessageHandler);
//                                                    ^^^^
//               The object to call the member function on