使用指向std :: shared_ptr的指向成员函数

时间:2016-05-27 19:48:16

标签: c++ pointer-to-member

我正在努力解决这段代码:

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

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

我收到编译错误:

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

node shared_ptr<node<T>>的位置与insert一样。

我已经尝试了我能猜到的一切,但仍然不知道发生了什么。

1 个答案:

答案 0 :(得分:1)

首先,函数调用操作符()的优先级高于->*,因此,您需要添加括号以强制执行所需的评估顺序。另外,node是智能指针,而指向成员函数的指针指的是存储在该共享指针中的类型。

话虽如此,您需要使用以下替代方案之一:

(*node.*get_son[index])();

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

(node.get()->*get_son[index])();
相关问题