The so-called generic lambda. Is the lambda that uses the auto type to indicate the specifier in the form declaration.
Example
Auto lambda = [] (auto x, auto y) {return x + y;};
According to the C++14 standard, this lambda acts the same as the following code.
struct unnamed_lambda{ template<typename T, TypeName u> auto Operator () (T x, U y) const {return x + y;}}; Auto lambda = Unnamed_lambda ();
C++14 's generic lambda can be seen as an upgraded version of the c++11 (mono-state) lambda. A single lambda is equivalent to a normal function object.
Generic lambda is equivalent to a function object with template parameters. Or a function template that is equivalent to a state. In comparison, the following results can be introduced:
- Single-state lambda is used within a function to capture peripheral variables to form closures that act as local functions. Generic Lambda reinforces this ability, which acts as a local function template.
- A single lambda can serve a higher-order function (a function that is a function), which acts as a callback function. Generic lambda reinforces this capability. Makes a generic callback possible.
- A single-state lambda can be used as a function return value to form a curry function (closure) for lambda calculus.
Generic Lambda reinforces this capability, making generic closures possible.
To be able to say, the generic lambda has greatly enhanced the FP (functional programming) capability of the C + + language due to the introduction of a single-state lambda.
#include <iostream> #include <string> #include <vector> #include <algorithm>using namespace std ; int main () {//generic local function auto F = [] (auto x, auto y) {return x + y;}; cout << F (1, 3) << endl;cout << f (string{}, "abc") << endl;//generic callback function Auto F2 = [] (auto e) {cout &L t;< e << ","; };vector<int> v1{1, 2, 3};vector<string> v2{"A", "B", "C"};for_each (V1.begin (), V1.end (), F2); cout << Endl;for_each (V2.begin (), V2.end (), F2); cout << endl;//generic closure Auto F3 = [] (auto a) {return [=] () mutable {return a = a + A;};}; Auto Twice1 = F3 (1); cout << Twice1 () << Endl; cout << Twice1 () << Endl;auto Twice2 = F3 (string{"A"}), cout << twice2 () << Endl; cout << twice2 () << Endl;} /*4abc1,2,3,a,b,c,24aaaaaa*/
C++14 early adopters: Generic Lambdas (Generic lambda)