【发布时间】:2018-04-19 09:04:49
【问题描述】:
我试图在 main 方法中调用指向 void * 函数的指针,编译器说的是 assigning to 'funcptr<g>' from incompatible type 'void *(void *)。 hello 函数实际上是 pthread_create 函数的参数。这就是为什么它是void * 函数。如何创建指向void * 函数的函数指针?
#include <iostream>
#include <pthread.h>
using namespace std;
template<typename T>
using funcptr = void (*T::*)(void *); // I think it is wrong here.
class m {
public:
template <typename T>
struct my_struct {
funcptr<T> ptr;
};
};
class g {
public:
static void *hello(void *);
};
int main() {
struct m::my_struct<g> h;
h.ptr = g::hello; // Error here
return 0;
}
【问题讨论】:
-
我不确定这样做的新方法是什么,但我总是这样做
typedef void (*funcptr)(void *); -
由于
hello是一个静态函数,所以不需要模板funcptr:using funcptr = void *(*)(void *);对于m类:class m { public: struct my_struct { funcptr ptr; }; };在main:struct m::my_struct h; h.ptr = &g::hello; // Take the address of hello -
使用std::thread,不要直接使用OS线程。
标签: c++ pthreads function-pointers void-pointers