0

I want to specify a function with parameters for a function parameter, but it doesn't come together.

////////////////////////////////////////////////////////////////////////

// Example funch...
void fileLoad(String path, String type) {
  file = SD.open(path.c_str(), FILE_READ);
  server.streamFile(file, type) != file.size();
  file.close();
}

// This is how I want to use it, but it's not possible:
server.on("/homepage", fileLoad("app/homepage.html", "text/html") );

////////////////////////////////////////////////////////////////////////

// Currently, as it works, you need 1 extra funch...:
void homepage() {
  fileLoad("app/homepage.html", "text/html");
}
server.on("/homepage", homepage);

4
  • 1
    How you want it isn't how C++ works. Depending on how "on" is written, and what you're actually using, you might be able to use a lambda, or you could start playing C++ games a la stackoverflow.com/a/41528436/438992. But I wouldn't. Jun 12 at 13:08
  • @DaveNewton, it does support std::function and so lambdas of the type that would be needed, so you could make that an answer.
    – timemage
    Jun 12 at 13:52
  • @timemage I don't remember enough C++ to be coherent ;) Jun 12 at 14:05
  • 1
    Well, I need more coffee, but I took a stab at it anyway. =)
    – timemage
    Jun 12 at 14:26
1

You can find examples of this sort of thing in the library's examples.

The on() function does support std::function as a parameter, which in turn, means you can use a C++11-onwards lambda expression (which Dave Newton mentioned in comments) to proxy your two-argument function call through a no-argument function:

server.on("/homepage", [] () {
    fileLoad("app/homepage.html", "text/html");
});

The [] ("capture list") is something that would be used if you wanted to copy or refer to things within the scope of the on function call. Since you're not doing that you could also just write a no-argument function which turns around and calls fileLoad with your two compile-time-known values. But it is common for people using this webserver library to need to make references things in scope.


As as side note, I'd consider not using String as your received parameter type in void fileLoad(String path, String type). When passing in a string literal, you're just causing dynamic allocation for no particularly good reason.

1

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