Lambda issue

Dec 27, 2011 at 9:26pm
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
unsigned char Override = 1;
// Without enclosing braces
int i = [&Override]()->int{ if(Override) return 5; else return 3; };
int j = [&]()->int{ if(Override) return 5; else return 3; };
int k = [Override]()->int{ if(Override) return 5; else return 3; };
int l = [=]()->int{ if(Override) return 5; else return 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!
Dec 27, 2011 at 9:57pm
The error is what the message says, you're trying to assign a lambda function to an int variable.

If you want to store the function itself, use auto:
auto f=[&](){if(Override)return 5;else return 3;};

If you want to get the result, you need to actually call the function:
int a=[&](){if(Override)return 5;else return 3;}();
Dec 27, 2011 at 10:01pm
Thanks, works perfectly.
I was using http://www.devx.com/cplus/10MinuteSolution/40553/1954 for help, and the ending () isn't mentioned anywhere. Lambda syntax is definitely the oddest C++ syntax.
Dec 27, 2011 at 10:19pm
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).
Last edited on Dec 27, 2011 at 10:31pm
Dec 28, 2011 at 2:21am
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()
{
	unsigned char Override = 1;

	// Assign the lambda function to a std::function object
	std::function<int()> func = [&Override]()->int{ if(Override) return 5; else return 3; };

	// Call the lambda function assigning its return value to an int
	int i = func();

	std::cout << i << '\n';
}
Last edited on Dec 28, 2011 at 2:22am
Topic archived. No new replies allowed.