Hello,
I decided to try out using a C++0x/C++11 lambda expression, which I am new to.
After checking for help online, I still can't get it to work, using any of the following methods:
1 2 3 4 5 6 7 8 9 10 11
unsignedchar Override = 1;
// Without enclosing braces
int i = [&Override]()->int{ if(Override) return 5; elsereturn 3; };
int j = [&]()->int{ if(Override) return 5; elsereturn 3; };
int k = [Override]()->int{ if(Override) return 5; elsereturn 3; };
int l = [=]()->int{ if(Override) return 5; elsereturn 3; };
// Or with braces
int m = [&Override]()->int{ if(Override) {return 5;} else {return 3;} };
int n = [&]()->int{ if(Override) {return 5;} else {return 3;} };
int o = [Override]()->int{ if(Override) {return 5;} else {return 3;} };
int p = [=]()->int{ if(Override) {return 5;} else {return 3;} };
All give:
error C2440: 'initializing' : cannot convert from '`anonymous-namespace'::<lambda0>' to 'int'
The code inside the lambda is fine, the error occurs in the '[' according to IntelliSense.
The 5 and 3 are enum variables in the real code, but these examples still produce the bug. I'm using VS10 Ultimate.
Any help would be appreciated. Thank you!
Lambda syntax is definitely the oddest C++ syntax.
Not really, it's pretty much the same as for normal functions, except that the return type and name is replaced by the square brackets (edit: and perhaps that it's an expression, not a declaration).
The thing to remember is that the lambda expression returns a lambda function rather than the return value of that function. To get that return value you need to actually call the function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
#include <functional>
int main()
{
unsignedchar Override = 1;
// Assign the lambda function to a std::function object
std::function<int()> func = [&Override]()->int{ if(Override) return 5; elsereturn 3; };
// Call the lambda function assigning its return value to an int
int i = func();
std::cout << i << '\n';
}