我正在尝试调用指向 void *
的指针main 方法中的函数和编译器说 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;
}
最佳答案
How can I create a function pointer to a void * function?
hello
is not a member function, but it's a static function.
所以你的funcptr
应该如下:
// No template needed.
using funcptr = void* (*)(void *)
请注意,hello
是用 static 声明的,meaning that it's no longer a member function to g
.
Static members of a class are not associated with the objects of the class.
因此使用 void (*T::*)(void *)
剔除非成员函数是不正确的。
如果您被允许使用支持 C++11 的编译器,您甚至不需要再手动推导其类型,使用 decltype :
// decltype deducts its exact type for you.
using funcptr = decltype(&g::hello);
class m
{
public:
struct my_struct
{
funcptr ptr;
};
};
仅供引用,由于 hello
没有其定义,因此您可能会遇到链接错误。为了防止这种情况,我假设里面有一些实现:
static void *hello(void *)
{
// Meaningless, but..
return nullptr;
}
关于c++ - 指向 void * 函数的指针 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47149859/