I was reading about delegation and I wanted to able to call within a base class any function pass as parameter depending on the event, so if for example I had a parser object and I want to assign what method from another object to call depending of what token is found. I did as bellow, it works but I am not sure if it's the proper way or if it's portable like too.
class base{
public:
typedef void (base::*methodPTR)();
methodPTR pfn;
void setMethod(methodPTR fn)
{
pfn = fn;
}
void run(){
if(pfn) (this->*pfn)();
}
};
class a : public base {
public:
};
class b : public base
{
a ob;
public:
void init()
{
//this function fn is not define neither in object "a" or "base"
//but still I can assign arbitrary member function just like I wanted
ob.setMethod(static_cast<base::methodPTR>(&b::fn));
}
void fn()
{
cout << "from class b!" << endl;
}
void test()
{
ob.run();
}
};
int _tmain(int argc, _TCHAR* argv[])
{
b x;
x.init();
x.test();
return 0;
}
ais used as member), which makes my answer useless. In short: Portable yes, proper way no!thiswhen you are calling the function. Just call it as(*fpn)();