Question

I have class

Class A{

};

typedef struct 
 {
  const char        *dec_text;
  void        (A::*TestFun)();

} Test ;

 Test _funs[] = {{"testLogOK", &A::testLogOK}, 
    {"testLoginException", &A::testLoginException}
};;

How can i initialize this Test Array in construct method. The _funs tracks the A's method name and corresponding address, the methods which like:

               void (methodName) (void)

In construction method, both below ways fail:

    _funs = {{"testLogOK", &A::testLogOK}, 
    {"testLoginException", &A::testLoginException}
};

The other question is how can i invoke the function pointer.. I tried the way like:

int
A::run (const char *name, int argc, ACE_TCHAR *argv[])
{
     for(int i=0; i< sizeof(_funs)/sizeof(Test); i++){
         Test test = _funs[i];
        *(test.testFun)();    //this->*(test.fun)();  Both fail with same error
                                //(this->*(test.fun))() works
        }
}     

The compile also fails with message:

 error C2064: term does not evaluate to a function taking 0 arguments

[UPdate]

I removed the struct Test and Test _funs out of Class A. But still have problem in A's method:

int   A::run (const char *name, int argc, ACE_TCHAR *argv[])

The testLogOK and testLoginException method do exist as member functions of class A

Was it helpful?

Solution

Try this:

class A
{
public:
    struct Test
    {
        const char        *dec_text;
        void        (A::*TestFun)();
    };
    A(Test tt[])
    {
        for (int i=0; tt[i].dec_text; i++)
            _funs[i] = tt[i];
    }
    void f1() { printf("this is f1\n"); }
    void f2() { printf("this is f2\n"); }
    void f3() { printf("this is f3\n"); }

    Test _funs[100];
};

A::Test tt[] = 
{
    { "Function f1", &A::f1},
    { "Function f2", &A::f2},
    { "Function f3", &A::f3},
    {0, 0}
};

void test()
{
    A a(tt);
    (a.*(a._funs[0].TestFun))();

    A *pa = new A(tt);
    (pa->*(pa->_funs[1].TestFun))();
    delete pa;

    // EDIT: call f3 
    (a.*(tt[2].TestFun))(); // this will call directly from the global table
}

This will invoke the function assigned to the pointer. This can be improved quite a bit if you typedef the pointer to the member

typedef void (A::*PF_T)();

and use a std::map as container:

std::map<std::string, PF_T> func_map;

It can be streamlined a lot more, but I hope it helps up to this point.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top