I am learning to write lambda expression in cpp, Below is the code. I'm using Visual Studio 2022 on Windows.
#include<iostream>
using namespace std;
int main()
{
int k = 98;
int l = 23;
auto lm_add = [k,l](int i, int j) {
return i + j;
};
cout << "addition using lambda : " << "cool" << lm_add << endl;
return 0;
}
I want to return the answer for given variables.
This
auto lm_add = [k,l](int i, int j) {
return i + j;
};
Initializes lm_add
with a lambda expression. Behind the scenes the compiler generates an unnamed unique type with a call operator with the specified signature, ie taking two integers, and with members for the captures (also two integers). That type has no <<
operator to pipe it to an outstream. It can be called:
std::cout << lm_add(k,l);
However, it captures k
and l
for no good reason. Perhaps you want to either capture the variables so you can call it without arguments:
auto lm_add = [k,l]() {
return k + l;
};
std::cout << lm_add();
Or not capture them an pass the argumetns:
auto lm_add = [](int i,int j) {
return i + j;
};
std::cout << lm_add(k,l);