Reputation: 2051
"error: invalid use of non-static data member ‘thread::tfun’"
Class thread {
typedef void* (th_fun) (void*);
th_fun *tfun;
void create(th_fun *fun=tfun) {
pthread_create(&t, NULL, fun, NULL);
}
}
How to have a function pointer inside a class?
Please note:- static deceleration will make the code compile. But my requirement is to hold the function per object.
Upvotes: 2
Views: 438
Reputation: 385144
Your use of pthreads is fine, and you have no pointer-to-member-function here.
The problem is that you're trying to use a non-static member variable as a default parameter for a function, and you can't do that:
struct T {
int x;
void f(int y = x) {}
};
// Line 2: error: invalid use of non-static data member 'T::x'
// compilation terminated due to -Wfatal-errors.
The default argument must be something that's — essentially — a global, or at least a name that doesn't require qualification.
Fortunately it's an easy fix!
Class thread {
typedef void* (th_fun) (void*);
th_fun* tfun;
void create(th_fun* fun = NULL) { // perfectly valid default parameter
if (fun == NULL) {
fun = tfun; // works now because there's an object
} // context whilst we're inside `create`
pthread_create(&t, NULL, fun, NULL);
}
};
Upvotes: 3
Reputation: 3432
You cannot do it using a non-static member function t
.
What you can do is passed the pointer of the class thread
to t
through the void *
parameter. Or if you still have other parameters for t
, you can wrap them all (including the point to class thread
) in a structure and pass the pointer of an instance of the structure.
As mentioned by others, only an extern "C"
function would fit the need of pthread_create
.
Upvotes: 0