简体   繁体   中英

How to pass a method of an object instance to a std::function type callback?

The evpp library has a callback method with following signature,

void evpp::TCPServer::SetMessageCallback(evpp::MessageCallback cb)

evpp::MessageCallback is in fact,

typedef std::function<void(const TCPConnPtr&, Buffer*)> MessageCallback;

I have a non-static method called worker inside HTTPTransport class and it has below signature,

void worker(const evpp::TCPConnPtr& conn, evpp::Buffer* msg, AnotherObject &instanceOfThat);

I attempt to attach this function into callback as follows,

evpp::EventLoop loop;
evpp::TCPServer server(&loop, "0.0.0.0:9000", "HTTPServer", 5);

HTTPTransport HTTPInterface;
AnotherObject instanceOfThat;

server.SetMessageCallback(std::bind(&HTTPTransport::worker, &HTTPInterface, &instanceOfThat));

But the compiler says,

no suitable user-defined conversion from "std::__2::__bind<void (HTTPTransport::*)(const evpp::TCPConnPtr &socket, evpp::Buffer *msg, AnotherObject &instanceOfThat), HTTPTransport *, AnotherObject*>" to "evpp::MessageCallback" exists

What am I doing wrong?

If you want to use std::bind() , you have to include placeholders for the arguments you are passing. Also, using & for the last argument is incorrect - what you need instead is std::ref() . Your expression becomes:

using namespace std::placeholders;  // for _1, _2
server.SetMessageCallback(std::bind(&HTTPTransport::worker, &HTTPInterface, _1, _2, std::ref(instanceOfThat)));

However, using a lambda is easier:

   server.SetMessageCallback([&](const TCPConnPtr& ptr, Buffer* buf)
   {
        return HTTPInterface.worker(ptr, buf, instanceOfThat); 
   } );

For what it's worth, I severely dislike std::bind. I always use a lambda. This might work:

void worker(const evpp::TCPConnPtr& conn, evpp::Buffer* msg) {
    ...
}

server.SetMessageCallback([=](const evpp::TCPConnPtr & conn, evpp::Buffer * buffer){ worker(conn, buffer); });

Your worker method then is just a standard method on your object. Get rid of the 3rd argument.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM