2017-03-02 25 views
0

std :: functionとstd :: bindでメソッドをバインドしようとすると問題が発生します。私CommunicationServiceクラスでBind std :: function error

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 :: _バインダー<のstd :: _凡、MessageContentから引数1を変換することはできません( RequestFunction '

「を' __cdecl 通信:: CommunicationService :: * )(スタンダード::文字列、MessageContent)、通信:: CommunicationService * CONST、CONSTはstd :: _ Phで< 1> &>

前に、私のRequestFunctionはそのようなものだった:

typedef std::function<void(std::string)> RequestFunction; 

、それが完全に働きました。 (すべての署名方法はもちろん調整されています)。

エラーの原因を理解できません。

this->httpServer->BindGET(
    [this](std::string uri, MessageContent msgContent) { 
    this->ManageGETRequest(std::move(uri), std::move(msgContent)); 
    } 
); 

+0

'ManageGetRequest'は2つのパラメータと' this'をとります。あなたは 'bind '' this'と一つのパラメータだけを与えます。 – NathanOliver

+1

'_2'がありません。 – Barry

+0

ありがとう、私はドキュメントをもっと慎重に見ていたはずです、私はstd :: bindが実際に動作していた方法を理解していない – Morgan

答えて

6

変更

this->httpServer->BindGET(
    std::bind(&CommunicationService::ManageGETRequest, this, std::placeholders::_1) 
); 

std::bindを使用すると、ほとんど常に悪い考えです。 Lambdaは同じ問題を解決し、ほとんどの場合、それを改善し、より良いエラーメッセージを出します。 std::bindにはラムダの機能が含まれている場合がほとんどありません。

std::bindは、lambdaと同時に標準にもたらされたboost::bindとしてpre-lambda C++ 11で書かれました。当時、ラムダにはいくつかの制限があったので、std::bindが意味を成し遂げました。しかし、これはlambdas C++ 11の制限が発生するケースの1つではなく、ラムダのパワーが増加して以来、std::bindの使用を学ぶことは、この時点で限界効用を大幅に減少させました。

std::bindをマスタリングしても、(バインドするバインド式をバインドするなどの)十分な厄介な癖があり、それには報酬がかかりません。

またでそれを修正することができます:

this->httpServer->BindGET(
    std::bind(&CommunicationService::ManageGETRequest, this, std::placeholders::_1, std::placeholders::_2) 
); 

が、私はあなたがすべきとは思いません。

関連する問題