2017-03-01 25 views
-1

在此示例中,如何將字符串傳遞給綁定的「處理函數」函數?嘗試傳遞字符串以綁定函數C++

// MyClass.h 

class MyClass { 
public: 
    MyClass(ESP8266WebServer& server) : m_server(server); 
    void begin(); 
    void handler(String path);  
protected: 
    ESP8266WebServer& m_server; 
}; 

// MyClass.cpp 
... 
void MyClass::begin() { 

    String edit = "/edit.htm"; 

    m_server.on("/edit", HTTP_GET, std::bind(&MyClass::handleFileRead(edit), this)); 
... 

每哪種方式我試試,我得到:需要

error: lvalue required as unary '&' operand 
+1

您正試圖*調用*'MyClass :: handler'作爲靜態成員函數。 –

+0

什麼是String類型的完整類型? –

+2

嘗試'm_server.on(uri,HTTP_GET,std :: bind(&MyClass :: handler,this,String(uri));'或者,也許lambda會工作,而不是:'String str_uri(uri); m_server.on uri,HTTP_GET,[this,str_uri](){this-> handler(str_uri);});' –

回答

2

當你

std::bind(&MyClass::handleFileRead(edit), this) 

您嘗試呼叫MyClass::handleFileRead(edit),並採取結果的指針作爲參數傳遞給std::bind通話。這當然是無效的,特別是因爲它不是作爲一個static成員函數的函數不返回任何內容以及..

你不應該通話的功能,只需將指針傳遞給它(和設置參數):

std::bind(&MyClass::handleFileRead, this, edit) 
//        ^ ^
// Note not calling the function here  | 
//          | 
//  Note passing edit as argument here 
+0

感謝兄弟,真棒回答。讓我走出負面的upvote將不勝感激。=) – 4m1r

0

左值作爲一元「&」操作數是說一個變量,需要採取從地址。在你的方法的情況下:

void begin(const char* uri) 
{ 
    m_server.on(uri, HTTP_GET, std::bind(&MyClass::handler(&path), this)); 
} 

path is undefined - 所以在這種情況下,路徑不是一個可尋址的變量。正如在上面的評論中提到的,通過@Remy Lebeau,如果你傳入參數uri - 那麼你有一個有效的可尋址變量。

+0

感謝喬治,我剛剛意識到最初的例子已經完全搞砸了。現在 – 4m1r

+0

啊,這很有道理! –