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.
-
Seems like more of a C++ question than an Arduino question.TheDoctor– TheDoctor2015年08月13日 15:10:29 +00:00Commented 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– Molda2015年08月13日 15:14:27 +00:00Commented Aug 13, 2015 at 15:14
-
It actually has nothing to do with the IDE per se.Ignacio Vazquez-Abrams– Ignacio Vazquez-Abrams2015年08月13日 16:46:47 +00:00Commented 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– Molda2015年08月13日 17:22:08 +00:00Commented Aug 13, 2015 at 17:22
-
It would happen with any editor, upload tool, or library. It is a language issue.Ignacio Vazquez-Abrams– Ignacio Vazquez-Abrams2015年08月13日 17:48:32 +00:00Commented Aug 13, 2015 at 17:48
3 Answers 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.
-
Static works. Hope i won't run into another issue by making it static though :) Thanks a lot.Molda– Molda2015年08月13日 17:28:26 +00:00Commented Aug 13, 2015 at 17:28
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));
-
If you have the Standard Template Library installed, yes.2015年10月03日 09:13:28 +00:00Commented Oct 3, 2015 at 9:13
This will get the job done - using anonymous function syntax:
server->on("/", [&]() {
handleRoot();
});