5

I need to pass a class member function to server.on, unfortunately i get an error.

error: no matching function for call to 'ESP8266WebServer::on

I have done some searching but could not understand anything I found. No simple explanation.

This works:

void handleRoot(){}
server.on("/", handleRoot);

This doesn't:

void myClass::handleRoot(){}
void myClass::setup(){
    server.on("/", handleRoot);
}

The second argument to server.on is

typedef std::function<void(void)> THandlerFunction;

Unfortunately I have no idea what it means.

mpromonet
  • 127
  • 6
Molda
  • 153
  • 1
  • 1
  • 5

3 Answers3

4

I've ben hitting this same problem.
Some further research on c++ syntax helped me find this clean solution, based on the

std::bind syntax:

server.on("/", std::bind(&myClass::handleRoot, this));
4

This will get the job done - using anonymous function syntax:

server->on("/", [&]() {
   handleRoot();
});
3

It's quite common question related to C++ programming.

The extensive explanation can be found here.

The short answer is: it's very different from taking the address of a regular function.

Workarounds (that might or might not work for you, depending on what else you need that function to do) are:

  • make it static
  • declare it as friend function, rather than member function

Either way, the point is that it should not be something associated to an instance of the class, but rather to the class as a whole.

Igor Stoppa
  • 2,125
  • 1
  • 14
  • 20
  • Static works. Hope i won't run into another issue by making it static though :) Thanks a lot. – Molda Aug 13 '15 at 17:28