2017-03-02 94 views
0

我試圖用std :: function和std :: bind綁定方法時遇到問題。綁定std ::函數錯誤

在我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 :: _粘結劑<的std :: _非受迫性,在messageContent轉換參數1( __cdecl 通信:: CommunicationService :: * )(的std :: string,在messageContent),通信:: CommunicationService * const的,常量性病:: _博士< 1> &>」到 'RequestFunction'

之前,我RequestFunction是這樣的:

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

它完美地工作。 (當然,所有簽名方法都會進行調整)。

我不明白是什麼導致了錯誤。

+0

'ManageGetRequest'接受兩個參數加'this'。你只給這個''綁定''和一個參數。 – NathanOliver

+1

你錯過了一個'_2'。 – Barry

+0

好的,謝謝,我應該更仔細地查看文檔,我不明白std :: bind如何實際工作 – Morgan

回答

6

變化

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幾乎總是一個壞主意。 Lambdas解決了同樣的問題,並且幾乎總是做得更好,並提供更好的錯誤信息。少數情況下,std::bind具有lambdas功能的地方並不是C++ 14所涵蓋的地方。

std::bind是寫在pre-lambda的C++ 11中的,因爲boost::bind然後帶入標準的lambdas同時在哪裏。那時,lambda有一些限制,所以std::bind是有道理的。但是,這不是lambda C++ 11限制發生的情況之一,並且隨着lambda在權力上的增長,學習使用std::bind在這一點上顯着減少了邊際效用。

即使你主人std::bind,它有足夠的煩人怪癖(如傳遞一個綁定表達式綁定),避免它有回報。

你也可以用修復:

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

,但我不認爲你應該。