Calling member function pointers from a member function

Here's roughly what I'm trying to do.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
//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.
Last edited on
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.
I tried x = (mymap[x])(); and got this

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])();
Oops, sorry, forgot about that (I normally use pointers to static functions). Try this instead:
 
x = (this->*mymap[x])();
That did it, Thanks!

For the second time tonight I've over-complicated things for myself. I think maybe it's time for bed.
Topic archived. No new replies allowed.