c++ - 如何通过函数指针递归调用类成员函数?
问题描述
我正在编写一个库来在树状对象上运行某些算法。我有一个edge_t
具有const unsigned int
数据成员的类edge_id
,weight
它们分别用作edge_t
的唯一标识符和边缘的权重。
我用 C++ 编写了tree_t
和subtree_t
类,它们都包含指向edge_t
s 的指针的映射。两者tree_t
和subtree_t
都派生自一个抽象basic_tree_t
类,该抽象类包含树状对象应该具有的所有功能,包括以下方法:
// returns the sum of the weights of the edge_ts below the edge_t pointed to by edge_ptr
unsigned int basic_tree_t::weight(const edge_ptr) const
// returns the number of edge_ts below the edge_t pointed to by edge_ptr
unsigned int basic_tree_t::num_descendents(const edge_ptr) const
我正在编写一些其他代码,其中用户输入一个tree_t
对象,并且代码必须从其中迭代地采样 a subtree_t
,进行一些计算,对另一个进行采样subtree_t
,进行更多的计算,等等。为了进行计算,代码需要知道每个子树中每条边的weight
值num_descendents
。
为了避免重复计算相同的值,每次我构建一个新的子树时,我都会创建std::map<unsigned int, unsigned int> weight_map
and std::map<unsigned int, unsigned int> num_descendents_map
,它将每个edge_id
子树的边缘映射到相应成员函数输出的值basic_tree_t
,然后使用这些值。我编写了以下函数来填充这些地图:
void populate_weight_map(subtree_t & S, edge_ptr & e, std::map<unsigned int, unsigned int> & weight_map)
{
weight_map.insert(std::pair<unsigned int, unsigned int>(e->edge_id, S.weight(e)));
for (auto & c : *(e->children))
if (S.contains(c))
populate_weight_map(S, c, weight_map);
}
void populate_num_descendents_map(subtree_t & S, edge_ptr & e, std::map<unsigned int, unsigned int> & num_descendents_map)
{
num_descendents_map.insert(std::pair<unsigned int, unsigned int>(e->edge_id, S.num_descendents(e)));
for (auto & c : *(e->children))
if (S.contains(c))
populate_weight_map(S, c, num_descendents_map);
}
这些在很大程度上是相同的函数,所以我认为编写一个将指向相关basic_tree_t
成员函数的指针作为第四个参数的函数会更有意义,如下所示:
void populate_map(subtree_t & S, edge_ptr & e, std::map<unsigned int, unsigned int> & m, unsigned int (basic_tree_t::*f)(const edge_ptr) const)
{
m.insert(std::pair<unsigned int, unsigned int>(e->edge_id, (S.*f)(e)));
for (auto & c : *(e->children))
if (S.contains(c))
populate_map(S, c, m, &basic_tree_t::*f); // ERROR ON THIS LINE!
}
但是,编译器在最后一行返回一个不透明的错误:
error: expected unqualified-id
populate_map(S, c, m, &basic_tree_t::*f);
^
第四个参数应该populate map
是什么?
解决方案
f
已经是指向所需成员的指针,所以只需传递:
populate_map(S, c, m, f);
&basic_tree_t::*f
在这种情况下没有任何意义。它看起来像是试图声明一个指向数据成员的指针,这无论如何都不是你想要的。
推荐阅读
- python - 我的代码使用 DHT 计算卷积有什么问题?
- reactjs - React 构建问题打开应用程序
- flutter - 在另一个可滚动视图后面传递的可滚动视图
- vue.js - 根据当前语言加载不同的 scss 文件 - nuxt
- javascript - 使用 JavaScript 检查 JSON 值/数组是否存在并在表格中显示数据
- java - 如何使用 crt 和 pkcs8_key 建立 http(s) url 连接 - java
- python - 如何为我的 html 烧瓶网站制作下载链接?
- docker - 即使已拉取所需的 docker 映像,为什么还需要 `--cache-from`?
- javascript - React Material UI:使用 withStyles 和 React Router 时 this.props 未定义
- postgresql - postgres 解析 json 以找到兼容的条目