title: C++11 lambda returning lambda
body: <p>this piece of code is not something unknown to JS developers</p>
  
  <pre><code>function get_counter()
  {
      return (
          function() {
              var c = 0;
              return function() { return ++c; };
          })();
  }
  </code></pre>
  
  <p>it basically creates a which creates different enumerators. So I was wondering if same thing can be done in C++11 with new lambda semantics? I ended up writing this piece of C++ which unfortunately does not compile!</p>
  
  <pre><code>int main()
  {
      int c;
      auto a = [](){
          int c = 0;
          return [&amp;](){
              cout &lt;&lt; c++;
          };
      };
      return 0;
  }
  </code></pre>
  
  <p>so I was wondering if there is a workaround to get it compiled and if there is how can compiler make this code run correctly? I mean it has to create separate enumerators but it should also collect garbage (unused c variables).</p>
  
  <p>by the way I'm using VS2012 compiler and it generates this error:</p>
  
  <pre><code>Error   2   error C2440: 'return' : cannot convert from 'main::&lt;lambda_10d109c73135f5c106ecbfa8ff6f4b6b&gt;::()::&lt;lambda_019decbc8d6cd29488ffec96883efe2a&gt;' to 'void (__cdecl *)(void)'    c:\users\ali\documents\visual studio 2012\projects\test\test\main.cpp   25  1   Test
  </code></pre>