c++0x lambdas,不让我作为函数ptr传递



我目前正在用C++0x编写一个程序,对此我还很陌生。
我正在设置对象之间的回调,并使用lambda来匹配类型(就像boost::bind()在某些方面所做的那样)

如果我调用asio库中的函数,如:

 socket_.async_read_some(buffer(&(pBuf->front()), szBuffer),                                                    
     [=](const boost::system::error_code &error, size_t byTrans) {                                               
                      this->doneRead(callBack, pBuf, error, byTrans); });

这编译良好,并按预期运行,从"async_read_some"回调"doneRead"

所以我在自己的代码中有一个类似的回调:

client->asyncRead([=](string msg){this->newMsg(msg); });

这只需要一个字符串,asyncReads原型如下

void ClientConnection::asyncRead(void(*callBack)(string)) 

但我得到了这个编译错误:

Server.cpp:在成员函数"void"中服务器::clientAccepted(std::shared_ptr,const boost::system::error_code&)':服务器.cpp:3:3:错误:不匹配用于调用的函数'ClientConnection::asyncRead(服务器::clientAccepted(std::shared_ptr,constboost::system::error_code&)::)'Server.cpp:31:3:注意:候选为:ClientConnection.h:16:9:note:voidClientConnection::asyncRead(void(*)(std::string))ClientConnection.h:16:9:注意:否参数1的已知转换'服务器::clientAccepted(std::shared_ptr,constboost::system::error_code&)::'到"void(*)(std::string)"

如何解决这个问题?

您的lambda隐式捕获this。捕获事物的lambda无法转换为原始函数指针。

因此,您需要编写asyncRead,以便它直接接受lambda函数对象,而不是让它转换为函数指针

template<typename CallbackType>
void ClientConnection::asyncRead(CallbackType callback);

或者,如果您不想将其作为模板编写,可以使用多态函数对象包装

void ClientConnection::asyncRead(std::function<void(string)> callBack);

我还考虑更改回调的接口,使其通过const引用接受字符串(除非所有回调实现都希望在内部修改或保存/移动传递的字符串,这在您的情况下似乎不太可能)。

最新更新