title: Generalizing C++11 Threads class to work with lambda
body: <p>I have a simple Threads class based on pthreads which works fine with a standard static callback function.</p>
  
  <p><strong>Is it possible to generalize Threads to work with lambdas, too?</strong></p>
  
  <p>problems:</p>
  
  <ul>
  <li><p>sandbox.cpp:27:26: error: invalid cast from type ‘main(int, char*<em>)::’ to type ‘void</em>’</p></li>
  <li><p><code>thread_cb()</code> needs to deal with generically casting <code>void*</code> back into something callable</p></li>
  </ul>
  
  <p>I suspect the second problem may be solved with template methods or maybe std::function, but not sure how.</p>
  
  <pre><code>#include &lt;vector&gt;
  #include &lt;iostream&gt;
  
  #include &lt;pthread.h&gt;
  
  class Threads 
  {
      public:
          Threads()  { }
          ~Threads() { }
  
      private:
          static void *thread_cb( void *v )
          {
              // following will also need to change
              void (*my_fptr)() =
                  reinterpret_cast&lt;void(*)()&gt;(reinterpret_cast&lt;long long&gt;(v));   
              my_fptr();
              return nullptr;
          }
  
      public:
          template&lt;typename CALLBACK&gt;
          void spawn( CALLBACK cb )
          {
              pthread_t t;
              void *p = (void*)( cb ); // problem here
              pthread_create( &amp;t, nullptr, thread_cb, p );
              m_threads.push_back( t );
          }
  
          void join_all()
          {
              for ( auto&amp; p : m_threads )
                  pthread_join( p, nullptr );
          }
  
      private:
          std::vector&lt; pthread_t &gt; m_threads;
  };
  
  static void my_cb()
  {
      std::cerr &lt;&lt; "bar" &lt;&lt; std::endl;
  }
  
  int main(int argc, char** argv)
  {
      Threads t;
  
      t.spawn( my_cb );  // ok
      t.spawn( []() { std::cerr &lt;&lt; "foo" &lt;&lt; std::endl; } ); // not ok
  
      t.join_all();
  
      return 0;
  }
  </code></pre>