[英]Bind std::function error
尝试使用std :: function和std :: 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)
RequestFunction typedef:
typedef std::function<MessageContent(std::string, MessageContent)> RequestFunction;
BindGET上的错误:
错误C2664:'无效的RESTServer :: BindGET(RequestFunction)':无法从'std :: _ Binder <std :: _ Unforced,MessageContent(__cdecl communication :: CommunicationService :: *)(std :: string,MessageContent)转换参数1 communication :: CommunicationService * const,const std :: _ Ph <1>&>'到'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
在lambda之前的C ++ 11中以boost::bind
编写,然后在同一时间将lambdas引入标准中。 当时,lambdas有一些限制,因此std::bind
才有意义。 但这不是lambdas C ++ 11限制出现的情况之一,并且随着lambda的力量不断增强,在这一点上学习使用std::bind
已大大减少了边际效用。
即使您精通std::bind
,它也有足够烦人的怪癖(例如传递绑定表达式以进行绑定),可以避免它带来收益。
您还可以使用以下方法修复它:
this->httpServer->BindGET(
std::bind(&CommunicationService::ManageGETRequest, this, std::placeholders::_1, std::placeholders::_2)
);
但是我不认为你应该这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.