Here’s the code.
#include<struct.h>
#include<iostream>
#include<functional>
using namespace std;
void LambdaTest(const function <struct dummy (void)>& f)
{
struct dummy test = f();
cout<<test.a<<endl;
}
int main()
{
int val = 5;
struct dummy dum;
auto func = [val](void) -> struct dummy
{
dummy temp;
temp.a = val;
return temp;
};
LambdaTest(func);
return 0;
}
The file struct.h is very simple.
struct dummy
{
int a;
};
GCC complains that
lambda_struct.cpp:19:38: error: field ‘temp’ has incomplete type
Is this allowed? If yes, then how do I fix it? If not, then why not?
EDIT:
The return type bug in the code (discovered by others) has now been fixed.
SOLUTION:
The problem is that C++0x standard allows definition to a new struct (and a class too, presumably) in the return type of a lambda definition itself. So if struct keyword is present in the return type, the compiler will think that it is a new type and begin to complain.
The fixed code is
#include<struct.h>
#include<iostream>
#include<functional>
using namespace std;
void LambdaTest(const function <struct dummy (void)>& f)
{
struct dummy test = f();
cout<<test.a<<endl;
}
int main()
{
int val = 5;
struct dummy dum;
auto func = [val](void) -> dummy
{
dummy temp;
temp.a = val;
return temp;
};
LambdaTest(func);
return 0;
}
The problem is that GCC incorrectly thinks you’re declaring a new struct type on the trailing return, and it declares a field of an incomplete type that is the same type GCC thinks you’re declaring.
It also complains that
on the line with the assignment, because it is expecting a member declaration, not a statement.
Changing to:
Will work.
Also, beware that not returning a value from a function will probably lead you into the realm of undefined behaviour.