title: Recursive call in lambda (C++11)
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/2067988/recursive-lambda-functions-in-c0x">Recursive lambda functions in c++0x</a>  </p>
  </blockquote>
  
  
  
  <p>Why can't I call a lambda recursively if I write it as:</p>
  
  <pre><code>auto a = [&amp;]
  { 
     static int i = 0; i++;
     std::cout &lt;&lt; i &lt;&lt; std::endl; 
     if (i&lt;10) 
       a(); //recursive call
  };
  </code></pre>
  
  <p>It gives compilation error (<a href="http://www.ideone.com/rvQkt" rel="nofollow noreferrer">ideone</a>):</p>
  
  <pre><code>prog.cpp:8:18: error: '((const main()::&lt;lambda()&gt;*)this)-&gt;main()::&lt;lambda()&gt;::a' cannot be used as a function
  
  prog.cpp: In function 'int main()':
  prog.cpp:9:9: error: variable 'auto a' with 'auto' type used in its own initializer
  </code></pre>
  
  <p>What does the error mean?</p>
  
  <p>I understand the reason why I can't write this:</p>
  
  <pre><code>auto i=i+1; //error: unable to deduce 'auto' from '&lt;expression error&gt;'
  </code></pre>
  
  <p>We can't write this because the type of <code>i</code> has to be deduced from it's initialization, which means the type cannot be deduced if <code>i</code> itself appears in the initialization (<a href="http://www.ideone.com/me0Oz" rel="nofollow noreferrer">ideone</a>). But how does it matter in case of lambda? If I'm not wrong, the type of a lambda is determined by it's parameter(s) and the return type; it doesn't depend on the body if it returns nothing (in which case, the return type is deduced as <code>void</code>, irrespective of other statements in the lambda-body).</p>
  
  <p>Anyway, I got a workaround, and I can use <code>std::function</code> instead as:</p>
  
  <pre><code>std::function&lt;void()&gt; a = [&amp;] 
  { 
     static int i = 0; i++;
     std::cout &lt;&lt; i &lt;&lt; std::endl; 
     if (i&lt;10) 
        a();
  };
  </code></pre>
  
  <p>which compile fines (<a href="http://www.ideone.com/5XK1B" rel="nofollow noreferrer">ideone</a>). But I'm still interested to know the reason why the <code>auto</code> version doesn't compile.</p>