2017-03-01 50 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

啊,这很有道理! –