Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
member function pointers with special function
#include <iostream>
#include <pthread.h>
/** Member function pointers given function name */
// class Launcher exists as a container of an instance and an argument.
// Using templates allows us to use the Launcher for a member of any class
template <class T>
class Launcher {
Launcher(T* _o, void* _arg) : o(_o), arg(_arg) {}
void* launch() { return (o->threadMe)(arg); }
T* o;
void* arg;
// a function with happily external linkage, which we will pass to
// pthread_create instead of the (internal) member function
template <class T>
void* LaunchMember(void* o) {
Launcher<T>* l = reinterpret_cast<Launcher<T>* >(o);
return l->launch();
class Bar {
Bar() : i(0) {}
int i;
class Foo {
void* threadMe(void* arg);
pthread_t fThread;
Bar bar;
Foo::Foo() {
bar.i = 42;
int arg = 12;
Launcher<Foo> l(this, (void*)&arg);
pthread_create(&fThread, NULL, LaunchMember<Foo>, &l);
pthread_join(fThread, NULL);
void* Foo::threadMe(void* arg) {
std::cout << "Foo::threadMe: *arg = " << *((int*)(arg)) << std::endl;
std::cout << "Foo::threadMe: bar.i = " << bar.i << std::endl;
int main(int argc, char* argv[]) {
Foo* f = new Foo();
return 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment