Reputation: 616
How can I pass a class member function to a non-class member function's parameter? I am getting the following compile error:
error: argument of type ‘void (MyNamespace::MyClass::)(int*)’ does not match ‘void (*)(int*)’
Library.h
typedef void (*testCallback)(int* iParam);
void UsingTheFoo(testCallback Callback);
Library.cpp
void UsingTheFoo(testCallback Callback)
{
int *p_int = new int;
*p_int = 5;
Callback(p_int);
}
MyClass.cpp
namespace MyNamespace
{
void MyClass::fooCB(int* a)
{
printf("hey! %d\n", *a);
}
void MyClass::testo()
{
UsingTheFoo(fooCB);
}
} // MyNamespace
I can not change the code in "Library", I need to use "UsingTheFoo" in MyClass member functions. I am aware my way is wrong, I searched and found similar questions but couldn't understand (braindead at the end of shift :) ) any of them completely to adapt for my problem.
I've already read: http://www.parashift.com/c++-faq-lite/pointers-to-members.html :S
Upvotes: 0
Views: 598
Reputation: 2109
A member function isn't a regular function.
Think of it as a function with signature
(className *pthis,...)
where .. is the signature you would think of.
You can still do this, but you would want std/boost::bind and a function object instead of a callback. Or as others have posted, you can make it static.
so perhaps you might want something like
typedef function<void (int*)> TCallback
void UsingTheFoo(TCallback, Callback);
MyClass class_object
with callback
TCallback cb = bind(std::ref(class_object),MyClass::fooCB);
Upvotes: 1
Reputation: 168626
fooCB
, in your example, must be a static class member:
class MyClass {
public:
static void MyClass::fooCB(int* a);
...
}
Upvotes: 0
Reputation: 2316
Make method that you wanna to pass as a callback as static. You've got this error because all methods have implicitly first parameter - pointer to an object, this, so their prototype doesn't correspond to callbacks'.
Upvotes: 2