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.

5
  • Seems like more of a C++ question than an Arduino question.
    – TheDoctor
    Aug 13, 2015 at 15:10
  • @TheDoctor you are probably right but I thought since it is related to arduino IDE someone could have same problem.
    – Molda
    Aug 13, 2015 at 15:14
  • It actually has nothing to do with the IDE per se. Aug 13, 2015 at 16:46
  • @Ignacio Vazquez-Abrams since I use arduino ide to write the code and to upload it to my esp8266 like many others do, it has a lot to do with it. Other people use same library and so they could have run into the same problem. Apart from that I really appreciate your useful comment.
    – Molda
    Aug 13, 2015 at 17:22
  • It would happen with any editor, upload tool, or library. It is a language issue. Aug 13, 2015 at 17:48

3 Answers 3

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.

1
  • Static works. Hope i won't run into another issue by making it static though :) Thanks a lot.
    – Molda
    Aug 13, 2015 at 17:28
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));
1
  • If you have the Standard Template Library installed, yes.
    – Nick Gammon
    Oct 3, 2015 at 9:13
4

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.