How can I create a class with an array of pointers to member functions?

I have a class, and I need to be able to access member functions via an array, how can I do this? Suppose we start with this:

1
2
3
4
5
6
7
8
9
10
11
class A
{
  A();

  void fun1();
  void fun2();
  void fun3();
  void fun4();

  void (*funarr)();
}


How will I go about setting this up so that funarr becomes an array of pointers to fun1,2,3,4 etc. Such that this will work:

1
2
3
4
5
6
int main()
{
  A a;

  (*a.funarr[2])(); // I've just triggered fun3() from the instance "a" of class A...
}
Hope this might be useful to you...please read it..
http://thecplusplusblog.blogspot.in/2009/04/using-array-of-pointer-to-member.html
Last edited on
Ok, I understand all that, but how do I go about making the array a member of the class? Where do I define it and how? Can it be on the stack? If so, how?

Also, as my function is declared and defined within the class, I don't need to prepend the "A::" part to "funarr" right?
Last edited on
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
struct A
{
  void fun1() {}
  void fun2() {}
  void fun3() {}
  void fun4() {}

  using mem_fun_ptr_t = decltype( &A::fun1 ) ;
  static const mem_fun_ptr_t funarr[] ;
};

const A::mem_fun_ptr_t A::funarr[] { &A::fun1, &A::fun2, &A::fun3, &A::fun4 } ;

#include <functional>
#include <array>

struct B
{
  void fun1() {}
  void fun2() {}
  void fun3() {}
  void fun4() {}

  static std::array< const std::function< void(B*) >, 4 > funarr ;
};

std::array< const std::function< void(B*) >, 4 > B::funarr
                        { { &B::fun1, &B::fun2, &B::fun3, &B::fun4 } } ;

int main()
{
    A a ;
    ( a.*A::funarr[2] )() ;

    B b ;
    B::funarr[2]( &b ) ;
}
JLBorges; I get the error "a class-qualified name is required" when I run this line:

using mem_fun_ptr_t = decltype( &Baseop::fun1 ) ;
Is Baseop the name of the class?

See http://liveworkspace.org/code/1qrd7X$1
Ah yes, sorry about that. The equivalent to your code would have been:

using mem_fun_ptr_t = decltype( &A::fun1 ) ;
EDIT: Thanks JLBorges, I seem to have got it working using the following, based on your suggestions:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Class A
{
  public:
  void fun1() {}
  void fun2() {}
  void fun3() {}
  void fun4() {}

  typedef void (A::*mem_fun_ptr_t)();
  static const mem_fun_ptr_t funarr[]; // array of function pointers
}

// define the array
  const A::mem_fun_ptr_t A::funarr[] = 
  {
  &fun1,
  &fun2,
  &fun3,
  &fun4
  };


Cheers
Last edited on
Topic archived. No new replies allowed.