title: Recursive lambda functions in C++14
body: <p>There is an oft-repeated 'trick' to write recursive lambda functions in C++11 that goes as follows:</p>
  
  <pre><code>std::function&lt;int(int)&gt; factorial;
  factorial = [&amp;factorial](int n)
  { return n &lt; 2 ? 1 : n * factorial(n - 1); };
  
  assert( factorial(5) == 120 );
  </code></pre>
  
  <p>(e.g. <a href="https://stackoverflow.com/q/2067988/726300">Recursive lambda functions in C++0x</a>.)</p>
  
  <p>This technique has two immediate drawbacks though: the target of the <code>std::function&lt;Sig&gt;</code> object is tied (via the capture by reference) to a very particular <code>std::function&lt;Sig&gt;</code> object (here, <code>factorial</code>). This means that the resulting functor typically cannot be returned from a function, or else the reference would be left dangling.</p>
  
  <p>Another (although less immediate) problem is that the use of <code>std::function</code> is typically going to prevent compiler optimizations, a side-effect of the need for type-erasure in its implementation. This is not hypothetical and can easily be tested.</p>
  
  <p>In the hypothetical situation where recursive lambda expressions would really be convenient, is there a way to address those issues?</p>