我在尝试使用 std::function 和 std::bind 绑定(bind)方法时遇到问题。
在我的 CommunicationService 类中:
this->httpServer->BindGET(std::bind(&CommunicationService::ManageGETRequest, this, std::placeholders::_1));
CommunicationService::ManageGetRequest 签名:
MessageContent CommunicationService::ManageGetRequest(std::string uri, MessageContent msgContent)
BindGET 签名:
void RESTServer::BindGET(RequestFunction getMethod)
请求函数类型定义:
typedef std::function<MessageContent(std::string, MessageContent)> RequestFunction;
BindGET 错误:
error C2664: 'void RESTServer::BindGET(RequestFunction)': cannot convert argument 1 from 'std::_Binder < std::_Unforced,MessageContent (__cdecl communication::CommunicationService::* )(std::string,MessageContent),communication::CommunicationService *const ,const std::_Ph < 1 > & >' to 'RequestFunction'
以前,我的 RequestFunction 是这样的:
typedef std::function<void(std::string)> RequestFunction;
而且效果很好。 (当然,所有签名方法都已调整)。
我不明白导致错误的原因。
最佳答案
改变
this->httpServer->BindGET(
std::bind(&CommunicationService::ManageGETRequest, this, std::placeholders::_1)
);
到
this->httpServer->BindGET(
[this](std::string uri, MessageContent msgContent) {
this->ManageGETRequest(std::move(uri), std::move(msgContent));
}
);
使用 std::bind
几乎总是一个坏主意。 Lambda 解决同样的问题,而且几乎总是做得更好,并提供更好的错误消息。 std::bind
具有 lambda 的功能的少数情况在 C++14 中大多没有涵盖。
std::bind
是用 pre-lambda C++11 编写的 boost::bind
然后同时引入标准的 lambdas where。当时,lambda 有一些限制,所以 std::bind
很有意义。但这不是 lambda C++11 限制发生的情况之一,并且随着 lambda 的发展,学习使用 std::bind
在这一点上显着减少了边际效用。
即使您掌握了 std::bind
,它也有足够烦人的怪癖(比如将绑定(bind)表达式传递给绑定(bind)),避免它会有返回。
您还可以通过以下方式修复它:
this->httpServer->BindGET(
std::bind(&CommunicationService::ManageGETRequest, this, std::placeholders::_1, std::placeholders::_2)
);
但我认为你不应该。
关于c++ - 绑定(bind) std::function 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42558244/