title: C++ lambda expression for method chains
body: <p>Let's say I have a <code>Car</code> object which also has an <code>Engine</code> member, and I want to inspect the properties of the object, calling some methods on <code>Car</code> and some methods in <code>Engine</code>. To get te info explicitly I could do </p>
  
  <pre><code>cout &lt;&lt; "my car has " &lt;&lt; mycar.GetEngine().NCylinders() &lt;&lt; " cylinders" &lt;&lt; endl;
  cout &lt;&lt; "my car has " &lt;&lt; mycar.NWheels() &lt;&lt; " wheels" &lt;&lt; endl;
  </code></pre>
  
  <p>all these calls are of the form <code>mycar.&lt;some method call chain here&gt;</code>. (you can also assume that they all have a compatible return types). How can I have a list of functors, so that I can pass an <code>Car</code> instance and it will execute the calls accordingly.?</p>
  
  <p>I have come up with a solution using <code>&lt;tr1/functional&gt;</code> using nested  binds.</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;tr1/functional&gt;
  #include &lt;map&gt;
  
  using namespace std;
  using namespace std::tr1;
  using namespace std::tr1::placeholders;
  
  struct Engine{
      int NCylinders() const {return 12;}
  };
  
  struct Car{
      int    NWheels() const {return 4;}
      Engine GetEngine() const {return myEngine;}
  private:
      Engine myEngine;
  };
  
  int main(){   
      Car mycar;
  
      map&lt;string,function&lt;double (const Car&amp;)&gt; &gt; carinfos;
      carinfos["cylinders"]   = bind(&amp;Engine::NCylinders,bind(&amp;Car::GetEngine,_1));
      carinfos["wheels"]      = bind(&amp;Car::NWheels,_1);
  
      map&lt;string,function&lt;double (const Car&amp;)&gt; &gt;::const_iterator info = carinfos.begin();
      for(;info!=carinfos.end();++info){
          cout &lt;&lt; "my car has: " &lt;&lt; (info-&gt;second)(mycar) &lt;&lt; " " &lt;&lt; info-&gt;first &lt;&lt; endl;
      }
  
      return 0;
  }
  </code></pre>
  
  <p>which outputs nicely:</p>
  
  <pre><code>my car has: 12 cylinders
  my car has: 4 wheels
  </code></pre>
  
  <p>But the nested binds can get ugly with longer chains or methods in the middle that have to have fixed arguments and I was wondering if there may be a solution using lambda expressions which could result in something like</p>
  
  <pre><code> //pseudocode
   carinfos["cylinders"]   = (_1.GetEngine().NCylinder());
   carinfos["wheels"]   = (_1.GetNWheel());
  </code></pre>
  
  <p>Edit:</p>
  
  <p>@KennyTM and @Kerrek SB have provided excellent answers using the new C++11 lambda expressions. I cannot yet use C++11, so I would appreciate solutions of similar conciseness using C++03</p>