Mor*_*gan 2 c++ stdbind c++11 std-function
尝试使用std :: function和std :: bind绑定方法时遇到问题.
在我的CommunicationService类中:
this->httpServer->BindGET(std::bind(&CommunicationService::ManageGETRequest, this, std::placeholders::_1));
Run Code Online (Sandbox Code Playgroud)
CommunicationService :: ManageGetRequest签名:
MessageContent CommunicationService::ManageGetRequest(std::string uri, MessageContent msgContent)
Run Code Online (Sandbox Code Playgroud)
BindGET签名:
void RESTServer::BindGET(RequestFunction getMethod)
Run Code Online (Sandbox Code Playgroud)
RequestFunction typedef:
typedef std::function<MessageContent(std::string, MessageContent)> RequestFunction;
Run Code Online (Sandbox Code Playgroud)
BindGET上的错误:
错误C2664:'void RESTServer :: BindGET(RequestFunction)':无法从'std :: _ Binder <std :: _ Unforced,MessageContent(__cdecl communication :: CommunicationService ::*)(std :: string,MessageContent)转换参数1, communication :: CommunicationService*const,const std :: _ Ph <1>&>'to'RequestFunction'
之前,我的RequestFunction是这样的:
typedef std::function<void(std::string)> RequestFunction;
Run Code Online (Sandbox Code Playgroud)
它工作得很好.(当然,调整了所有签名方法).
我不明白导致错误的原因.
更改
this->httpServer->BindGET(
std::bind(&CommunicationService::ManageGETRequest, this, std::placeholders::_1)
);
Run Code Online (Sandbox Code Playgroud)
至
this->httpServer->BindGET(
[this](std::string uri, MessageContent msgContent) {
this->ManageGETRequest(std::move(uri), std::move(msgContent));
}
);
Run Code Online (Sandbox Code Playgroud)
使用std::bind
几乎总是一个坏主意.Lambdas解决了同样的问题,并且几乎总是做得更好,并提供更好的错误消息.少数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)
);
Run Code Online (Sandbox Code Playgroud)
但我不认为你应该这样做.
归档时间: |
|
查看次数: |
2027 次 |
最近记录: |