[英]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, evpp
库有一个带有以下签名的回调方法,
void evpp::TCPServer::SetMessageCallback(evpp::MessageCallback cb)
evpp::MessageCallback
is in fact, evpp::MessageCallback
实际上是,
typedef std::function<void(const TCPConnPtr&, Buffer*)> MessageCallback;
I have a non-static method called worker
inside HTTPTransport
class and it has below signature,我在
HTTPTransport
class 中有一个名为worker
的非静态方法,它具有以下签名,
void worker(const evpp::TCPConnPtr& conn, evpp::Buffer* msg, AnotherObject &instanceOfThat);
I attempt to attach this function into callback as follows,我尝试将此 function 附加到回调中,如下所示,
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.如果你想使用
std::bind()
,你必须为你传递的 arguments 包含占位符。 Also, using &
for the last argument is incorrect - what you need instead is std::ref()
.此外,对最后一个参数使用
&
是不正确的 - 您需要的是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:但是,使用 lambda 更容易:
server.SetMessageCallback([&](const TCPConnPtr& ptr, Buffer* buf)
{
return HTTPInterface.worker(ptr, buf, instanceOfThat);
} );
For what it's worth, I severely dislike std::bind.对于它的价值,我非常不喜欢 std::bind。 I always use a lambda.
我总是使用 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.那么您的工作方法只是 object 上的标准方法。 Get rid of the 3rd argument.
摆脱第三个论点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.