C ++: pointer to class member function inside unrelated structure

I've read a bit on the internet about how to do this, and I think I'm doing it right ... My goal is to have an array of structural objects containing pointers to member functions of a class.

Here's what I have so far ...

typedef void (foo::*HandlerPtr)(...);
class foo
{
public:
    void someFunc(...);
    // ...
private:
    // ...
};

struct STRUCT
{
    HandlerPtr handler;
};

STRUCT stuff[]
{
    {&foo::someFunc}
};

      

Then when calling a function using (stuff [0]. * Handler) () with or without arguments (I really intend to use argument lists), I get a "handler": Undeclared identifier ...

I must be missing something, I just don't know what.

+2


source to share


1 answer


someFunc () is not a static method, so you need to instantiate the foo object in order to call someFunc () through your method pointer variable, i.e.

foo f;
f.*(stuff[0].handler)();

      

Or:

foo f;
HandlerPtr mthd = stuff[0].handler;
f.*mthd();

      



Or, using pointers:

foo *f = new foo;
f->*(stuff[0].handler)();
delete f;

      

Or:

foo *f = new foo;
HandlerPtr mthd = stuff[0].handler;
f->*mthd();
delete f;

      

+8


source







All Articles