Listing 3: Wrapping the thread pointer in an intermediate object

#include <pthread.h>

template <class T>
class WrapperSub;

template <class T>
class Thread {
protected:
   pthread_t _threadptr;
   void Run() { }
public:
   void Create() 
   { pthread_create(&_threadptr, NULL, thread_func, 
        new WrapperSub<T>(this)); } 
   ~Thread() { pthread_join(_threadptr, NULL); }
   friend void *thread_func(void *);
   friend class WrapperSub<T>;
};

class Wrapper {
public:
   virtual void Wrap()=0;
   virtual ~Wrapper(){}
};

template <class T>
class WrapperSub : public Wrapper {
protected:
   Thread<T> *_t;
public:
   WrapperSub(Thread<T> *t) : _t(t) {}
   void Wrap() {
      _t->Run();
   }
};

void *thread_func(void *p) {
   Wrapper *w=reinterpret_cast<Wrapper *>(p);
   if (w) {
      w->Wrap();
      delete w;
   }
}

int main() {
   Thread<int> t;
   t.Create();
   return 0;
}