title: Achieving clean lambda functions in C++11
body: <p>I've been playing around a lot with the new C++11 lambda's, and the requirement to fully specify the template argument is a real drag. The syntax I would <em>like</em> to be using is something similar to the following:</p>
  
  <pre><code>#include &lt;vector&gt;
  #include &lt;algorithm&gt;
  
  struct foo
  {
      void bar() {}
  };
  
  int main()
  {
      vector&lt;foo&gt; v(10);
  
      for_each(v.begin(), v.end(), [](f) {f.bar();});
                                     ^^^
  }
  </code></pre>
  
  <p>Is there any way to get anything approximately close to this? Boost's Phoenix library is OK, but the syntax for calling member functions requires <em>lots</em> of boiler plate - I guess I'm after C++11's ease of calling member functions coupled with Phoenix's automatic deduction of type.</p>
  
  <p><strong>Current idea</strong></p>
  
  <p>I have gotten it down to this syntax:</p>
  
  <pre><code>vector&lt;foo&gt; x(1);
  vector&lt;bar&gt; y(1);
  for_each(x.begin(), x.end(), [](_a f) {f-&gt;f();});
  for_each(y.begin(), y.end(), [](_a b) {b-&gt;b();});
  </code></pre>
  
  <p>Which works, but you have to add the capability per type (eg. <code>ADD_AUTO_LAMBDA_SUPPORT(foo);</code>). It also has the limitation that all supported types can not have any ambiguous members.</p>
  
  <p>The full code for that is:</p>
  
  <pre><code>#include &lt;vector&gt;
  #include &lt;algorithm&gt;
  #include &lt;iostream&gt;
  
  using namespace std;
  
  struct foo
  {
      foo() : x(3) {}
      int x;
      void f() { cout &lt;&lt; x &lt;&lt; endl;}
  };
  
  struct bar
  {
      bar() : y(133.7) {}
      double y;
      void b() { cout &lt;&lt; y &lt;&lt; endl;}
  };
  
  struct combo : foo, bar { };
  
  struct _a
  {
      _a(foo&amp; f) : offset(reinterpret_cast&lt;combo*&gt;(&amp;f)) {}
      _a(bar&amp; b) : offset(reinterpret_cast&lt;combo*&gt;((char*)&amp;b - 2*sizeof(foo))) {}
  
      combo* operator-&gt;() { return offset; }
  
  private:
      combo* offset;
  };
  
  int main()
  {
      vector&lt;foo&gt; x(1);
      vector&lt;bar&gt; y(1);
  
      for_each(x.begin(), x.end(), [](_a f) {f-&gt;f();});
      for_each(y.begin(), y.end(), [](_a b) {b-&gt;b();});
  }
  </code></pre>
  
  <p>You could then use some template and preprocessor magic to generate both <code>_a</code> and <code>combo</code>, but the issue comes when you have ambiguous names (eg. a third struct with a <code>b()</code> function - you need a way to disambiguate them that I can't think of at the moment.</p>