I want to pass a class method (bounded to an object) to a function in a library that asks for a non-const reference to a callable.
It would work perfectly fine with std::bind, if the parameter was not asked by reference. I don't know why it's asked by reference and i can't change it.
Is there a way to make the result of std::bind an lvalue ? Or should i rework everything ?
Here is a code that shows the problem:
#include <iostream>
#include <functional>
#include <string>
using namespace std::placeholders;
// code in a lib that i cannot change
class Agent {
public:
template <typename functor>
void register_handler(functor & f) {
// f is stored in data member "functor & f_;" of connection_event_generic_dispatcher in initializer list of ctor.
std::auto_ptr<details::connection_event_dispatcher_base> monitor(new details::connection_event_generic_dispatcher<functor>(f));
pimpl_base_->register_connection_event_monitor(monitor);
}
};
// code i can edit
class PersistentConnection {
public:
PersistentConnection(): data_member_("world") {
agent_.register_handler(std::bind(&PersistentConnection::internal_handler, this, _1));
}
private:
void internal_handler(std::string message) {
std::cout << message << " " << data_member_ << std::endl;
}
std::string data_member_;
Agent agent_;
};
int main (int argc, char** argv) {
PersistentConnection p;
return 0;
}
the compilation command line and error:
clang++ --std=c++11 /tmp/test.cpp -o /tmp/test
/tmp/test.cpp:20:10: error: no matching member function for call to 'register_handler' agent_.register_handler(std::bind(&PersistentConnection::internal_handler, this, _1)); ~~~~~~~^~~~~~~~~~~~~~~~ /tmp/test.cpp:10:7: note: candidate function [with functor = std::_Bind)> (PersistentConnection *, std::_Placeholder<1>)>] not viable: expects an l-value for 1st argument void register_handler(functor & f) { ^ 1 error generated.