2011-05-28 30 views
4

我目前正在用C++ 0x編寫一個程序,這是我很新的。
我設置了對象之間的回調和使用lambda匹配類型(如boost::bind()做的方式)C++ 0x lambda,不讓我作爲函數ptr傳遞

如果我像ASIO庫調用一個函數:

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

編譯沒有問題,和正如所料,「doneRead」運行被稱爲從「async_read_some」

所以我有一個類似的回調在我自己的代碼後面:

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

這需要只是一個字符串,並asyncReads原型如下

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

但我得到這個編譯錯誤:

Server.cpp: In member function ‘void Server::clientAccepted(std::shared_ptr, const boost::system::error_code&)’: Server.cpp:31:3: error: no matching function for call to ‘ClientConnection::asyncRead(Server::clientAccepted(std::shared_ptr, const boost::system::error_code&)::)’ Server.cpp:31:3: note: candidate is: ClientConnection.h:16:9: note: void ClientConnection::asyncRead(void (*)(std::string)) ClientConnection.h:16:9: note: no known conversion for argument 1 from ‘Server::clientAccepted(std::shared_ptr, const boost::system::error_code&)::’ to ‘void (*)(std::string)’

如何這個問題得到解決?

+0

你能分享Server :: clientAccepted。看起來您正在使用提供的回調,並且clientAccepted函數接受的lambda類型與您傳遞的內容之間存在不匹配。 – 2011-05-28 22:41:37

回答

10

您的lambda隱式捕獲this。捕獲事物的lambda不能轉換爲原始函數指針。

所以你需要寫asyncRead所以它直接接受,而不是讓它轉換成一個函數指針

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

或者,如果你不想寫這爲模板的lambda函數對象,您可以使用多態函數對象包裝

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

我也會考慮改變回調的接口,以便其接受const引用的字符串(除非所有的回調實現本質上要修改或保存/月在內部傳遞字符串,這在你的情況下似乎不太可能)。

+0

所以我不假設你知道你是否第二種方式是提升它的方式嗎?我正在嘗試這種方式。 – 111111 2011-05-28 22:56:42

+0

是的,這(第二)似乎已經感到它,感謝噸兄弟。 – 111111 2011-05-28 23:19:25