Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy can't I declare a struct variable inside a lambda in c++0x?
    text
    copied!<p>Here's the code.</p> <pre><code>#include&lt;struct.h&gt; #include&lt;iostream&gt; #include&lt;functional&gt; using namespace std; void LambdaTest(const function &lt;struct dummy (void)&gt;&amp; f) { struct dummy test = f(); cout&lt;&lt;test.a&lt;&lt;endl; } int main() { int val = 5; struct dummy dum; auto func = [val](void) -&gt; struct dummy { dummy temp; temp.a = val; return temp; }; LambdaTest(func); return 0; } </code></pre> <p>The file struct.h is very simple.</p> <pre><code>struct dummy { int a; }; </code></pre> <p>GCC complains that </p> <blockquote> <p>lambda_struct.cpp:19:38: error: field ‘temp’ has incomplete type</p> </blockquote> <p>Is this allowed? If yes, then how do I fix it? If not, then why not?</p> <p><strong>EDIT:</strong></p> <p>The return type bug in the code (discovered by others) has now been fixed. </p> <p><strong>SOLUTION:</strong></p> <p>The problem is that C++0x standard allows definition to a new struct (and a class too, presumably) in the <em>return type</em> 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.</p> <p>The fixed code is </p> <pre><code>#include&lt;struct.h&gt; #include&lt;iostream&gt; #include&lt;functional&gt; using namespace std; void LambdaTest(const function &lt;struct dummy (void)&gt;&amp; f) { struct dummy test = f(); cout&lt;&lt;test.a&lt;&lt;endl; } int main() { int val = 5; struct dummy dum; auto func = [val](void) -&gt; dummy { dummy temp; temp.a = val; return temp; }; LambdaTest(func); return 0; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload