title: How to create an std::function from a move-capturing lambda expression?
body: <p>I'm trying to create an <code>std::function</code> from a move-capturing lambda expression. Note that I can create a move-capturing lambda expression without problems; it's only when I try to wrap it in an <code>std::function</code> that I get an error.</p>
  
  <p>For example:</p>
  
  <pre><code>auto pi = std::make_unique&lt;int&gt;(0);
  
  // no problems here!
  auto foo = [q = std::move(pi)] {
      *q = 5;
      std::cout &lt;&lt; *q &lt;&lt; std::endl;
  };
  
  // All of the attempts below yield:
  // "Call to implicitly-deleted copy constructor of '&lt;lambda...."
  
  std::function&lt;void()&gt; bar = foo;
  std::function&lt;void()&gt; bar{foo};
  std::function&lt;void()&gt; bar{std::move(foo)};
  std::function&lt;void()&gt; bar = std::move(foo);
  std::function&lt;void()&gt; bar{std::forward&lt;std::function&lt;void()&gt;&gt;(foo)};
  std::function&lt;void()&gt; bar = std::forward&lt;std::function&lt;void()&gt;&gt;(foo);
  </code></pre>
  
  <p>I'll explain why I want to write something like this. I've written a UI library which, similar to jQuery or JavaFX, allows the user to handle mouse/keyboard events by passing <code>std::function</code>s to methods with names like <code>on_mouse_down()</code>, <code>on_mouse_drag()</code>, <code>push_undo_action()</code>, etc. </p>
  
  <p>Obviously, the <code>std::function</code> I want to pass in should ideally use a move-capturing lambda expression, otherwise I need to resort to the ugly "release/acquire-in-lambda" idiom I was using when C++11 was the standard:</p>
  
  <pre><code>std::function&lt;void()&gt; baz = [q = pi.release()] {
      std::unique_ptr&lt;int&gt; p{q};
      *p = 5;
      std::cout &lt;&lt; *q &lt;&lt; std::endl;
  };
  </code></pre>
  
  <p>Note that calling <code>baz</code> twice would be an error in the above code. However, in my code, this closure is guaranteed to be called exactly once.</p>
  
  <p>BTW, in my real code, I'm not passing an <code>std::unique_ptr&lt;int&gt;</code>, but something more interesting.</p>
  
  <p>Finally, I'm using Xcode6-Beta4 which uses the following version of clang:</p>
  
  <pre><code>Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)
  Target: x86_64-apple-darwin13.3.0
  Thread model: posix
  </code></pre>