Re: How to pass function pointer by reference?
On 28 Mai, 04:09, Immortal Nephi wrote:
[...] What if you want to invoke member function like this below.
void B::F1( const A &ra )
void C::F1( const A &ra )
Pass Member Function by Reference will only work one object if
you use B object or C object.
This sounds familiar. Isn't it practically the same question you asked
in a previous thread? And didn't you already get an answer there?
You want to write non-templated function in your library that takes a
"call back" as parameter of some type that should support calling non-
static member functions of some bound object of various classes.
A type-safe variant is possible (via something like boost::function)
but you probably have to make sure that both, your library and the
client's code, is compiled with the same version of boost::function
(or whatever replacement you use). So, the binary interface is a bit
fragile.
The other option (the C way of doing this) would be to use a plain
function pointer in combination with a void pointer that stores some
user-defined address:
// non-templated library function
void run( void(*pf)(void*), void* context )
{
pf(context);
}
class C {
void f();
};
void invoke_C_f(void* ctx) {
static_cast<C*>(ctx)->f();
}
int main() {
C c;
run(&invoke_C_f,&c);
}
You just need to be careful with the pointer types. Here, C* is
converted implicitly to void* and back again to C* which is guaranteed
to be lossless. But the type information is lost with void* which is
why you can't rely on the conversion C* -> void* -> D* (where D is a
base class of C) to give you the same result as C* -> D*. The latter
conversion might include an automatic pointer adjustment.
Cheers!
SG