Generic pointer to a generic class method

Hi guys,

When something like as follows is written,

void (ClassA::* method_pointer)();

it's possible to assign all kind of methods from ClassA that returns void, like

method_pointer = &ClassA::method1;

But... Is it possible anyway to leave the class restriction and assign methods from different classes ??

I'd like to do that "method_pointer" sometimes could point out &ClassA::method1, sometimes &ClassB::method1... etc...

Thanks,
Last edited on
Do you mean a templated functor that is given an object and a reference to member?
@keskiverto,

Thanks... Googling I find this page: http://www.newty.de/fpt/functor.html
Last edited on
FWIW, you don't have to reinvent the wheel here. C++11 offers the std::function class which is extremely flexible.

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
#include <iostream>
#include <functional>
using namespace std;

// 2 unrelated classes
class A
{
public:
    void func() { cout << "in A::func\n"; }
};

class B
{
public:
    void func() { cout << "in B::func\n"; }
};

int main()
{
    A a;
    B b;

    function<void()> f;  // a generic function that returns void and takes no params

    f = bind(&A::func, &a);
    f(); // <- calls a.func();


    f = bind(&B::func, &b);
    f(); // <- calls b.func()
}


http://ideone.com/OyV2B4
Topic archived. No new replies allowed.