Question

I want to send a function pointer as a parameter for another function, but my function refuses to accept member functions of a class as a parameter. I have tried send a nonmember function and a member function as a parameter and it only compiles when I use nonmember functions. I need to send a member function so I have access to variables.

Here is the function call that works:

daSocket->beginReceive(chuckTesta, fakePayload);

here is the header for chuckTesta():

void chuckTesta(std::string *message, ssError& e, void *payload)

The compiler is completely silent...

Here is the function call that DOES NOT works:

daSocket->beginReceive(client::passwordAttemptCallback, fakePayload);

here is the header for client::passwordAttemptCallback():

void client::passwordAttemptCallback(std::string *message, ssError& e, void *payload)

the compiler says:

client2.cpp: In member function ‘void client::enterPassword()’:
client2.cpp:45: error: no matching function for call to ‘StringSocket::beginReceive(<unresolved overloaded function type>, void*&)’
../StringSocket/StringSocket.h:53: note: candidates are: void StringSocket::beginReceive(StringSocket::receiveCallback, void*)

here is header for StringSocket::beginReceive():

void beginReceive(receiveCallback callBack, void* payload);

where a receiveCallback is:

typedef boost::function<void (string *message, ssError& e, void *payload) > receiveCallback;

Why does this work with nonmember functions but fail with member functions?

Was it helpful?

Solution 2

You cannot send member function pointers. One way to get the same result is, creating a non-member function that takes, all the member function's parameters and a reference to that class's object and then call that member function on that object.

i.e.

class A{
 void func(int a, int b){
 }
 static void nonMemberFunc(A * a, int b, int c){
   a -> func(b, c)
 }
}

Now, pass nonMemberFunc and this as a pointers.

OTHER TIPS

Because (non-static) member functions and non-member functions are entirely different beasts. A non-static member function expects an extra this parameter; it is implicit, but the boost::function object still needs to pass it somehow. What you could construct is a

boost::function<void (client*, string *message, ssError& e, void *payload)>

which would then work just fine. However, what you probably really want is to use Boost.Bind and construct your boost::function like this:

bind(&client::passwordAttemptCallBack, &myClient, _1)

which will make &myClient be passed for that place.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top