Skip to content

Instantly share code, notes, and snippets.

@mastbaum
Created January 24, 2012 05:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mastbaum/1668136 to your computer and use it in GitHub Desktop.
Save mastbaum/1668136 to your computer and use it in GitHub Desktop.
member function pointers with mysterious superclass
#include <iostream>
#include <pthread.h>
/** Calling a member function using a mysterious superclass */
#include <stdio.h>
class Super;
typedef void* (Super::*pSuperMF)(void*);
// 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 {
public:
Launcher(T* _o, pSuperMF _f, void* _arg) : o(_o), f(_f), arg(_arg) {}
void* launch() {
return (o->*f)(arg);
}
T* o;
void* a;
pSuperMF f;
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 {
public:
Bar() : i(0) {}
int i;
};
class Super {
public:
virtual void* threadMe(void* arg) {
std::cout << "Super::threadMe" << std::endl;
}
};
class Foo : public Super {
public:
Foo();
void* threadMe(void* arg);
private:
pthread_t fThread;
Bar bar;
};
Foo::Foo() {
bar.i = 42;
int arg = 12;
Launcher<Super> l(this, &Super::threadMe, (void*)&arg);
pthread_create(&fThread, NULL, LaunchMember<Super>, &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