【问题标题】:Pointer to a void * function C++指向 void * 函数 C++ 的指针
【发布时间】: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是一个静态函数,所以不需要模板funcptrusing funcptr = void *(*)(void *);对于m类:class m { public: struct my_struct { funcptr ptr; }; };在main:struct m::my_struct h; h.ptr = &amp;g::hello; // Take the address of hello
  • 使用std::thread,不要直接使用OS线程。

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


【解决方案1】:

如何创建指向 void * 函数的函数指针? hello 不是成员函数,而是 静态 函数。

所以你的funcptr 应该如下:

// No template needed.
using funcptr = void* (*)(void *)

请注意,hello 是用 static 声明的,meaning that it's no longer a member function to g

类的静态成员与类的对象相关联。

所以使用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;
}

【讨论】:

  • 谢谢!!正是我需要的。
【解决方案2】:

如果您使用的是 C++11,则可以使用 std::function&lt;&gt;,它只关心函数的返回类型和参数,而不是它们的定义位置和类型。

这是使用std::function&lt;&gt;的代码

#include <iostream> 
#include <functional>
#include <pthread.h> 

using namespace std; 

class m { 
public: 
    template <typename T> 
    struct my_struct { 
        function<void*(void*)> ptr;
    };
}; 

class g { 
public: 
    static void *hello(void *) {
        cout<<"Hello.."<<endl;
    }
}; 

int main() { 
    struct m::my_struct<g> h; 
    h.ptr = g::hello;
    h.ptr(nullptr);

    return 0; 
}

【讨论】:

  • 当只需要一个简单的函数指针时,std::function 是多余的。另外,这个问题没有答案:“如何创建指向 void * 函数的函数指针?”
猜你喜欢
  • 1970-01-01
  • 2010-09-29
  • 2011-07-31
  • 1970-01-01
  • 2013-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多