I am currently writing a program in C++0x which I am fairly new to.
I am setting up callbacks between objects and using lambda to match the types (like boost::bind()
does in ways)
If I call a function in the asio library like:
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 back from 'async_read_some'
so I have a similar call back in my own code:
client->asyncRead([=](string msg){this->newMsg(msg); });
This takes just a string, and asyncReads prototype is as follows
void ClientConnection::asyncRead(void(*callBack)(string))
But I get this compile error:
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)’
How can this issue be resolved?
Your lambda captures this
implicitly. A lambda that captures things cannot convert to a raw function pointer.
So you need to write asyncRead
so it accepts the lambda function object directly, instead of letting it convert to a function pointer
template<typename CallbackType>
void ClientConnection::asyncRead(CallbackType callback);
Alternatively, if you don't want to write this as a template, you can use a polymorphic function object wrapper
void ClientConnection::asyncRead(std::function<void(string)> callBack);
I would also consider changing the callback's interface so it accepts the string by const reference (unless all the callback implementations inherently want to modify or save/move the passed string internally, which seem unlikely in your case).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With