C ++ 0x lambdas not allowing me to pass as a ptr function

I am currently writing a program in C ++ 0x, for which I am pretty newbie.
I set up callbacks between objects and using lambda to match types (e.g. boost::bind() does in ways)

If I call a function in the asio library, for example:

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

This compiles fine and runs as expected; 'doneRead' is called from 'async_read_some'

so I have a similar call in my own code:

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

It only takes a line, and the asyncReads prototype is as follows

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

But I get this compilation error:

Server.cpp: in the member function 'void Server :: clientAccepted (stand :: shared_ptr, const boost :: system :: error_code &): Server.cpp: 31: 3: error: there is no matching function to call "ClientConnection :: asyncRead (Server :: clientAccepted (stand :: shared_ptr, Const raise :: System :: Error_Code &): :) Server.cpp: 31: 3: note: candidate: ClientConnection.h: 16: 9: note: void ClientConnection: : asyncRead (invalidated (*) (std :: string)) ClientConnection.h: 16: 9: note: there is no known conversion for argument 1 of "Server :: clientAccepted (stand :: shared_ptr, Const raising :: System :: Error_Code &) :: to 'void (*) (std :: string)

How to solve this problem?

+4
source share
1 answer

Your lambda captures this implicitly. A lambda that captures things cannot convert to a raw function pointer.

So, you need to write asyncRead so that it asyncRead lambda function object directly, instead of letting it convert to a function pointer

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

Alternatively, if you do not want to write this as a template, you can use the wrapper of the polymorphic function object

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

I would also think about changing the callback interface so that it accepts the string via the const link (if all callback implementations essentially do not want to change or save / move the passed string inside, which seems unlikely in your case).

+10
source

All Articles