Reputation: 691
I need to pass a pointer to a member function as an argument to a member function in another class. What I'm doing is something like below. I want to call int Processor::AddJob(void (_pFunc)(void*), void* _pArg) method with void* ProcessHandler::Task(void* a) as the first argument. I did it as
TaskFunc pFunc1 = &ProcessHandler::Task;
p_Processor->AddJob(pFunc1,10);
But it gives the error
error: no matching function for call to Processor::AddJob(void* (ProcessHandler::&)(void), int)’ Processor.h:47: note: candidates are: int Processor::AddJob(void* ()(void), void*)
Can someone please help me on this.My implementation is as follows.(Not the exact code-it is much larger than this)
class Processor
{
public:
Processor();
virtual ~Processor();
int AddJob(void *(*_pFunc)(void*), void* _pArg);
};
int Processor::AddJob(void *(*_pFunc)(void*), void* _pArg)
{
//Job addition related code goes here
}
/////////////////////////////////////////////////////////////////////////////
typedef void* (ProcessHandler::*TaskFunc)(void*);
class ProcessHandler
{
public:
ProcessHandler(Processor* _pProcessor);
virtual ~ProcessHandler();
void* Task(void* a);
void Init();
private:
Processor* p_Processor;
};
void* ProcessHandler::Task(void* a)
{
//Task related code goes here
}
void ProcessHandler::Init()
{
TaskFunc pFunc1 = &ProcessHandler::Task;
p_Processor->AddJob(pFunc1,10); //This give the compile error.
}
/////////////////////////////////////////////////////////////////////////
int main()
{
Processor* pProcessor = new Processor();
ProcessHandler* pProcessHandler = new ProcessHandler(pProcessor);
pProcessHandler->Init();
}
Upvotes: 1
Views: 395
Reputation: 2598
void (_pFunc)(void*) is a C-Function pointer, and as such, you can only either pass C-Functions via that pointer, or static functions.
void (ProcessHandler::*)(void); //Since you already have a Typedef, pass that as 'type'
should help you call a member function. Call it with the pointer to member function calling syntax:
(objectPointer->*functionPointer)();
Upvotes: 0
Reputation: 2017
In C++ I would suggest to do_NOT use pointers to functions(raw pointers are arguable too). You should use std::function(boost::function) for more generality, or template. Latter gives you a bit perfomance, but less typecheck.
Upvotes: 1
Reputation: 1248
You can only pass static member functions via the address-of operator. Regular member functions don't work. You should consider using std::function.
Upvotes: 3