//Main////////////////////////////////////////////
int main(int argc, char **argv)
{
Wid *wid = new Wid();
wid->WidCheBox(..., &Wid::Eve, ...); //Results in an error
return 0;
}
The error I receive is of the following sort:
...no known conversion for argument 3 from ‘void (Wid::*)(Cli*)’ to ‘void (EveCli::*)(Cli*)’
The rational for this type of coding was to create something of a generic function pointer (EveCli) which all classes could inherit from (such as Wid) in order to better facilitate the passing of function pointers.
But so far, all my attempts to get it to work have been in vain and I'm at a loss for a solution.
@JLBorges
is this really possible? how does virtual function pointer work?
On line 10: how does p know that fn is foo or bar and that the derived function has to be called?
> how does p know that fn is foo or bar and that the derived function has to be called?
A typical implementation is for the pointer to contain sufficient information to tell the compiler:
a. Is this a pointer to a virtual function?
b. If it is, what is its offset into the vtable?
c. If it is, does the this pointer need adjustment? If it does need adjustment, how is it to be adjusted?
Of course... if you're using C++11... the easier way to do this is with std::function and std::bind. That way the function can be anywhere and doesn't need to be limited to any one class.
#include <functional>
typedef std::function<void (int)> Callback; // void (int); is the callback signature
void call_it( Callback func, int param )
{
func( param ); // <- very natural calling syntax
}
// some functions we can use to callback. First, a member of any class/struct
struct SomeStruct
{
void someFunc(int param)
{
//...
}
};
// and also a global
void someGlobalFunc(int param)
{
//...
}
int main()
{
SomeStruct s;
Callback member = std::bind( &SomeStruct::someFunc, &s ); // bind to a member
// the 2nd param to bind is the 'this' pointer for someFunc. In this case, it would be
// like calling s.someFunc
call_it(member,5); // works as you'd expect: calls s.someFunc(5)
// binding to a global var is just as easy
Callback global = std::bind( &someGlobalFunc );
call_it(global,5); // also works as you'd expect: calls someGlobalFunc(5)
}
You can also use bind to rearrange/supply parameters if the function signature differs. But I'll wait on giving examples of that unless you're really interested.