title: Mutually recursive lambdas
body: <p>This is a boost::asio udp echo demo based on a <a href="http://www.boost.org/doc/libs/1_53_0/doc/html/boost_asio/example/echo/async_udp_echo_server.cpp" rel="nofollow">boost asio example</a>.</p>
  
  <p>The meat of this version using C++ lambda is less than half the size of the boost example one, but gcc tells me that <code>received</code> is not visible in <code>recv_from</code>.</p>
  
  <p>It pains me to have to write this in a more verbose manner.  Can some C++ guru help me with a trick to define mutually recursive lambdas?</p>
  
  <pre><code>class server {
  public:
    server(io_service&amp; io_service, short port)
      : socket_(io_service, udp::endpoint(udp::v4(), port)) {
      auto recv_from = [&amp;,received]() {
        socket_.async_receive_from(buffer(data_, max_length), sender_endpoint_,
                                   received);
      };
      auto received = [&amp;,recv_from](const error_code&amp; error, size_t bytes_transferred) {
        if (!error &amp;&amp; bytes_transferred &gt; 0) {
          socket_.async_send_to(buffer(data_, bytes_transferred), sender_endpoint_,
                                [&amp;](const error_code&amp;, size_t) {
                                  recv_from();
                                });
        } else {
          recv_from(); // loop
        }
      };
      recv_from();
    }
  
  private:
    udp::socket socket_;
    udp::endpoint sender_endpoint_;
    enum { max_length = 1024 };
    char data_[max_length];
  };
  </code></pre>
  
  <p>Edit, solution: I needed to add this:</p>
  
  <pre><code>std::function&lt;void(const error_code&amp;, size_t)&gt; received;
  </code></pre>
  
  <p>to make it easy for the type-inference engine (I'm spoiled having programmed Haskell)</p>
  
  <p>Edit2: There are lifetime issues so that won't work.</p>