Search code examples
c++functionpointersoperator-precedencepointer-to-member

issue with using pointer to member function


This line of code has been giving me a load of trouble:

while(!list.add(list.*get().children()));

It is out of context, but Im simply trying to use the class member function pointer get(). Can someone please offer constructive feedback?

struct State
{
    State *children();
};
class List
{
    State *getBFS();
    State *getDFS();
    State *getUCS();
    State *getGS();
    State *getAStar();
public:
    State *(List::*get)();
    bool add(State *state);
    List(short type)
    {
        switch(type)
        {
        case 0: get = &List::getBFS;
            break;
        case 1: get = &List::getDFS;
            break;
        case 2: get = &List::getUCS;
            break;
        case 3: get = &List::getGS;
            break;
        default: get = &List::getAStar;
        }
    }
};
int main()
{
    List list(0);
    while(!list.add((list.*get()).children()));
}

Solution

  • Note that the precedence of operator() is higher than operator.*, so you should change

    list.*get()
    

    to

    (list.*get)()
    

    EDIT

    What you want should be

    while(!list.add(((list.* list.get)())->children()));
    //                       ~~~~~       ~~
    

    Note (1) get is a member of List; (2) the return type of get is a pointer (i.e. State*), so you should use -> instead of ..