I am working in ESP8266 AsyncWebserver library and have been using this [](parameter)
as an argument to some functions as shown below but does not really know what it means. Being a neophyte I am curious to know what does this convention means, its functionalities and how to use it. Hopefully experts here would help me with this.
server.on("/page",HTTP_GET,[](AsyncWebServerRequest * request){
some code....;
request->getParam("Param1")->value();
});
1 Answer 1
That is called a lambda expression and it's a way of including the content of a function as a parameter anonymously instead of writing an actual function and using the name of it.
It's shorthand for:
void myCallback(AsyncWebServerRequest * request) {
// some code....;
request->getParam("Param1")->value();
}
// ...
server.on("/page", HTTP_GET, myCallback);
It does have a few benefits over traditional functions at the expense of readability, such as the ability to "capture" local variables from the surrounding scope.
-
Thanks Mr.@Majenko, I will look further about this topic. So in the above example instead of creating a new function as a callback they used lambda function on the go to use locally within the function scope itself Am I right. Im just curious to know can we use the variables declared in server.on function inside the lambdaMr.B– Mr.B2020年04月27日 10:19:32 +00:00Commented Apr 27, 2020 at 10:19
-
2All is explained in the link. But any variable that is defined within the function that
server.on
appears in can be "captured" by placing it between the[...]
, so you can then use it from within the lambda expression itself.Majenko– Majenko2020年04月27日 10:22:22 +00:00Commented Apr 27, 2020 at 10:22 -
Thanks Mr.@Majenko thats usefulMr.B– Mr.B2020年04月27日 11:17:44 +00:00Commented Apr 27, 2020 at 11:17
-
2More generally, the lambda is actually shorthand for a class declaration somewhere in the enclosing scope,
struct unnamed_lambda_helper { /* captured local variables are data members of this class */ auto operator()(/* arguments here */) -> /* return type here, if specified */ { /* body here */ } };
, and then the expression creates an instance of this class.HTNW– HTNW2020年04月27日 18:48:16 +00:00Commented Apr 27, 2020 at 18:48 -
1@PeterMortensen It is a C++11 feature (meaning older compilers may not support it). Of course, other languages do have their own version of this. To the best of my knowledge, C does not.Cort Ammon– Cort Ammon2020年04月28日 00:45:31 +00:00Commented Apr 28, 2020 at 0:45