C++14 Generalized Lamda is an enhancement over C++11 Lamda feature. In previous article Lambda expression in C++11and C++14 we have discussed c++11 Lamda expression.  Let us see below simple example code and imagine what could be an issue.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

auto f = [](int n) { cout<<n<<endl; };
int main()
{
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(5);
v.push_back(4);
v.push_back(8);
for_each(v.begin(),v.end(),f);

return 0;
}

The above code will print vector elements. The vector is containing integers, accordingly we have defined our lamda expression [](int n){ cout<<n<<endl;}. In The lamda syntax expression the (int n) has integer type parameter. So for the different parameters we have to modified lamda expression.

Lambda expression in C++11and C++14

In the above program if vector contains float or double data type the lamda expression would be [](float n){cout<<n<<endl;}. But there is C++14 enhancement over c++11 lamda. C++14  introduces generalized lamda expression. Basically we can use auto key word in C++14 lamda expression.  See below code using generalized lamda.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

auto f = [](auto n) { cout<<n<<endl; };
int main()
{
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(5);
v.push_back(4);
v.push_back(8);
for_each(v.begin(),v.end(),f);
// vector with float
vector<int> vf;
vf.push_back(1.2);
vf.push_back(2.4);
vf.push_back(5.2);
vf.push_back(4.0);
vf.push_back(8.7);
for_each(vf.begin(),vf.end(),f);
return 0;
}

Note: the above code will compile as

g++-4.9.1 -std=c++14 -pedantic vecto.cpp -o test


Related Contents to follow