Search code examples
c++pointer-to-member

Using pointer-to-member functions with std::shared_ptr


I'm struggling with this piece of code:

typedef shared_ptr<node <T>> (node<T>::*son_getter)();
    son_getter get_son[] = {&node<T>::getLeftSon, &node<T>::getRightSon};

insert = node->*get_son[index]();

I get a compilation error:

error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘get_son[index] (...)’, e.g. ‘(... ->* get_son[index]) (...)’
 insert = node->*get_son[index]();

Where node is shared_ptr<node<T>> just as insert is.

I've tried everything I could guess and still no idea what's going on.


Solution

  • First of all, a function call operator () has a higher priority than ->*, as such, you need to add parenthesis to enforce the desired evaluation order. Additionally, node is a smart pointer, while the pointer to member function refers to the type stored in that shared pointer.

    Having said that, you need to use one of the below alternatives:

    (*node.*get_son[index])();
    
    (&*node->*get_son[index])(); // or std::addressof(*node)->*
    
    (node.get()->*get_son[index])();