Search code examples
c++arduinoarduino-esp8266

Trying to pass a String to bound function C++


In this example, how do you pass a String to the bound "handler" function?

// 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));
...

Every which way I try I get:

error: lvalue required as unary '&' operand

Solution

  • When you do

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

    you attempt to call MyClass::handleFileRead(edit), and take the pointer of the result as the argument to the std::bind call. This is of course not valid, especially since the function doesn't return anything as well as it's not being a static member function..

    You should not call the function, just pass a pointer to it (and set the argument):

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