dimanche 23 août 2015

C++ method pointer array

I have a class which has several methods. Now I would like to have this class have an array of method pointers which can be called with an instance of the class.

Basically like this

class MyClass
{
public:
    MyClass(int aInit);

    typedef int (MyClass::*myPtr)(int);
    const myPtr ptrArray[2];
    const myPtr ptrSingle;

    int plus(int b);
    int minus(int b);

private:
    int a;
};

With an implementation like the following:

MyClass::MyClass(int aInit) :
    ptrArray({&MyClass::plus, &MyClass::minus}),
    ptrSingle(&MyClass::plus)
{
    this->a = aInit;
}

int MyClass::plus(int b)
{
    return (this->a + b);
}

int MyClass::minus(int b)
{
    return (this->a - b);
}

From an other class, I have this method using MyClass in which I try to access the function pointer members:

MyClass myInstance(10);
MyClass::myPtr function = myInstance.ptrSingle;
int ret1 = function(1);
int ret2 = myInstance.ptrArray[0](1);
int ret3 = myInstance.ptrArray[1](1);

This leads to the folliwing error messages:

error: must use '.*' or '->*' to call pointer-to-member function in 'function (...)', e.g. '(... ->* function) (...)'
     int ret1 = function(1);
                          ^
error: must use '.*' or '->*' to call pointer-to-member function in 'myInstance.MyClass::ptrArray[0] (...)', e.g. '(... ->* myInstance.MyClass::ptrArray[0]) (...)'
     int ret2 = *(myInstance.ptrArray[0])(1);
                                           ^
error: must use '.*' or '->*' to call pointer-to-member function in 'myInstance.MyClass::ptrArray[1] (...)', e.g. '(... ->* myInstance.MyClass::ptrArray[1]) (...)'
     int ret3 = myInstance.ptrArray[1](1);
                                        ^

  1. I don't know where to put the *, and I also don't know why a dereference is necessary here. With C, as far as I remember, this should not be necessary when calling a function pointer. I have read that it should be something like (this->*temp.set_func)(value); but how can I adapt this syntax to my problem? myInstance is not a member of the class, so I have no this. Also, myInstance is not a pointer, so I don't see why * should be necessary. Can anybody help me with this?
  2. When I initialize the myPtr like this const myPtr ptrArray[] = {&MyClass::plus, &MyClass::minus};, the compiler complains too many initializers for 'int (MyClass::* const [0])(int)'. But shouldn't be such initializations for non int types be possible with c++11?

I am using gcc (Gentoo 4.9.3 p1.0, pie-0.6.2) 4.9.3 with c++11.

Aucun commentaire:

Enregistrer un commentaire