I'm fairly new to C++ and trying to use an existing library ("WebServer").
I guess the language supports what I'm trying to do. I'm wrestling with getting the syntax right.
I'm struggling with correctly setting up a parameter which has type std::function<void(void)>
.
In the snippets below, WebServer
is the library class. I'm trying to use its "on" method, which requires a parameter of type THandlerFunction
.
The compiler throws errors when I try to setup the THandlerFunction
parameter and assign it to fhandleRootPageRequest
.
Some similar-sounding problems suggested using std::mem_fn()
. std::mem_fn
looks promising. However, I'm getting some confusing compiler error messages back.
How do I correctly setup fhandleRootPageRequest
, so I can call WebServer::on
with its THandlerFunction
parameter pointing to method WebServerInterface::handleRootPageRequest
?
class WebServer {
public:
typedef std::function<void(void)> THandlerFunction;
void on(const Uri& uri, THandlerFunction fn);
...
};
...
class WebServerInterface {
public:
WebServerInterface() {};
void begin() {
WebServer::THandlerFunction fhandleRootPageRequest = &WebServerInterface::handleRootPageRequest; // Does not compile
webServerCPP.on("/", fhandleRootPageRequest);
}
void handleRootPageRequest() {
webServerCPP.send(200, "text/html", "<!doctype html> <html> <head> <body> <div> <h1>Hello World</h1> </div> </body> </html>");
private:
WebServer webServerCPP;
}
};
// Examples of what I've tried. Variations on the fhandleRootPageRequest theme. Do not compile.
WebServer::THandlerFunction fhandleRootPageRequest = &WebServerInterface::handleRootPageRequest;
// error: conversion from 'void (WebServerInterface::*)()' to non-scalar type 'WebServer::THandlerFunction' {aka 'std::function<void()>'} requested
WebServer::THandlerFunction fhandleRootPageRequest = std::mem_fn(&WebServerInterface::handleRootPageRequest);
// error: conversion from 'std::_Mem_fn<void (WebServerInterface::*)()>' to non-scalar type 'WebServer::THandlerFunction' {aka 'std::function<void()>'} requested
WebServer::THandlerFunction fhandleRootPageRequest = (WebServer::THandlerFunction) std::mem_fn(&WebServerInterface::handleRootPageRequest);
// error: no matching function for call to 'std::function<void()>::function(std::_Mem_fn<void (WebServerInterface::*)()>)'