c++ - 指向 void * 函数的指针 C++

标签 c++ pthreads function-pointers void-pointers

我正在尝试调用指向 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/

相关文章:

c++ - linux:如何断开远程用户访问?

c++ - 从 C 中的多个线程访问静态常量变量

c - 读取函数指针变量值

c++ - C++中运算符重载的语法是什么?

c++ - 在 C++ 中,是否可以强制用户捕获异常?

c++ - pthread 互斥锁定和解锁每个变量

C 线程参数

c++ - 如何在 C/C++ 中默认初始化函数指针?

c++ - 为什么函数指针定义与任意数量的符号 '&' 或星号 '*' 一起使用?

c++ - 对一个数组进行排序,然后对另外两个数组进行排序