//A.h----------------------------
#include <map>
class A{
map <int,int(A::*)()> mymap;
void fill_map();
public:
int f1();
int f2();
int f3();
void go();
A()
: mymap(){fill_map();go();}
};
//A.cpp----------------------
#include "A.h"
void A::fill_map()
{
mymap[1]=&A::f1;//pretend the functions are defined somewhere
mymap[2]=&A::f2;
mymap[3]=&A::f3;
}
void A::go(
{
int x=1;
while (x!=-1)
{
int (A::*final)()=mymap[x];
//call function and store result in x here
}
}
How do I call a member function pointer from a member function?
The idea is to have a bunch of functions that call each other via returning the int that's tied to the next function in the map. This way it can run indefinitely.
Don't you normally just call like like a normal function? As in, you just have in the "go" function:
1 2 3 4 5 6
void A::go() {
int x = 1;
while (x != -1) {
x = (mymap[x])();
}
}
I don't have a compiler with me, so I can't check to see if that works, but I think it should.
Also, have you considered using function objects (or std::function) instead? That can simplify the program a lot, as well as making it easier to maintain.
error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘((A*)this)->A::mymap.std::map<_Key, _Tp, _Compare, _Alloc>::operator[]<int, int (A::*)(), std::less<int>, std::allocator<std::pair<const int, int (A::*)()> > >((*(const key_type*)(& x))) (...)’, e.g. ‘(... ->* ((A*)this)->A::mymap.std::map<_Key, _Tp, _Compare, _Alloc>::operator[]<int, int (A::*)(), std::less<int>, std::allocator<std::pair<const int, int (A::*)()> > >((*(const key_type*)(& x)))) (...)’
x=(mymap[x])();