title: C++11 Passing function as lambda parameter
body: <p>Recently, I encountered a weird problem with passing a function passed as a parameter to a lambda expression. The code compiled just fine with clang 3.5+, but failed with g++ 5.3 and I wonder whether the problem is in the c++ standard, a non-standard extension in clang, or an invalid syntactic interpretation in GCC.</p>
  
  <p>The example code is fairy simple:</p>
  
  <pre><code>    template&lt;typename Fn, typename... Args, typename T = typename std::result_of&lt;Fn(Args...)&gt;::type&gt;
      std::future&lt;T&gt;
      async(Fn &amp;&amp;fn, Args &amp;&amp;... args)
      {
          std::shared_ptr&lt;std::promise&lt;T&gt;&gt; promise = std::make_shared&lt;std::promise&lt;T&gt;&gt;();
          auto lambda = [promise, fn, args...](void)
              { promise-&gt;set_value(fn(std::move(args)...)); };
          send_message(std::make_shared&lt;post_call&gt;(lambda));
          return promise-&gt;get_future();
      };
  </code></pre>
  
  <p>GCC reported the following:</p>
  
  <pre><code>error: variable ‘fn’ has function type
               { promise-&gt;set_value(fn(std::move(args)...)); };
  (...)
  error: field ‘async(Fn&amp;&amp;, Args&amp;&amp; ...) [with Fn = int (&amp;)(int, int); Args = {int&amp;, int&amp;}; T = int]::&lt;lambda()&gt;::&lt;fn capture&gt;’ invalidly declared function type
           auto lambda = [promise, fn, args...](void)
  </code></pre>
  
  <p>Fortunately, I found a simple workaround, adding a std::function object, encapsulating the function parameter:</p>
  
  <pre><code>    template&lt;typename Fn, typename... Args, typename T = typename std::result_of&lt;Fn(Args...)&gt;::type&gt;
      std::future&lt;T&gt;
      async(Fn &amp;&amp;fn, Args &amp;&amp;... args)
      {
          std::shared_ptr&lt;std::promise&lt;T&gt;&gt; promise = std::make_shared&lt;std::promise&lt;T&gt;&gt;();
          std::function&lt;T(typename std::remove_reference&lt;Args&gt;::type...)&gt; floc = fn;
          auto lambda = [promise, floc, args...](void)
              { promise-&gt;set_value(floc(std::move(args)...)); };
          send_message(std::make_shared&lt;post_call&gt;(lambda));
          return promise-&gt;get_future();
      };
  </code></pre>
  
  <p>Although I don't fully understand what was wrong in the first piece of code, that successfully compiled with clang and run without errors.</p>
  
  <hr>
  
  <p><strong>EDIT</strong></p>
  
  <p>I've just noticed, that my solution fails catastrophically, if one of the arguments was supposed to be a reference. So if you have any other suggestions that might work with C++11 (i.e. without specialized lambda captures [c++14 feature]), it would be really cool...</p>