将指向成员的指针函数与 std::shared_ptr 结合使用

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

本文关键字:shared ptr 结合 std 成员 函数 指针      更新时间:2023-10-16

我正在为这段代码而苦苦挣扎:

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一样。

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

首先,函数调用运算符()具有比->*更高的优先级,因此,您需要添加括号以强制执行所需的求值顺序。此外,node 是一个智能指针,而指向成员函数的指针是指存储在该共享指针中的类型。

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

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