I ran into this problem a couple of months ago while working on my senior project project. This requires some knowledge of the underlying mechanics of C ++.
The main problem is that function pointers are different from member function pointers. This is because member functions have an implicit first parameter, this
.
On the man
page:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
Thread entry point void* (*)(void*)
. Your Base::action
function is of type void* (Base::*)()
. The Base::
this ugly type declaration denotes the this
type. The type difference is why the compiler does not accept your code.
We have to fix two things to make this work. We cannot use a member function because pointers to member functions do not bind this
to an instance. We also need a single parameter of type void*
. Fortunately, these two corrections go hand in hand, because the solution is to explicitly pass this
yourself.
class Base { public: virtual void* action() = 0; protected: pthread_t tid; friend void* do_action(void* arg) { return static_cast<Base*>(arg)->action(); } }; class Derived : public Base { public: Derived() {
Edit: Woops, if tid
is protected
or private
, then do_action
should be friend
.
source share