Reputation: 5370
Say I have a function foo
:
void foo(void (*ftn)(int x))
{
ftn(5);
}
It needs as a parameter a void
function that accepts an int as a parameter. Consider
void func1(int x) {}
class X {
public:
void func2(int x) {}
};
Now
foo(&func1)
is ok.
But foo(&X::func2)
isn't ok because X::func2
isn't static and needs a context object and its function pointer type is different.
I tried foo(std::bind(&X:func2, this))
from inside X
but that raises a type mismatch too.
What is the right way of doing this?
Upvotes: 0
Views: 142
Reputation: 302852
Based on the comments, if you cannot change the signature of foo
to take anything but a raw function pointer... then you'll have to do something like this:
struct XFunc2Wrapper {
static X* x;
static void func2(int v) {
x->func2(v);
}
};
And then just do foo(&XFunc2Wrapper::func2)
once you set XFunc2Wrapper::x
to be your X
. It doesn't have to be nested in a struct, it can just be some global pointer, but nesting helps establish the intent behind the code better.
But this should definitely be last resort after (as per Captain Obvlious) trying to do foo(std::function<void(int)> )
.
Upvotes: 2