如何通过函数指针递归调用类成员函数?



我正在编写一个库来在树状对象上运行某些算法。 我有一个edge_t类,它有const unsigned int个数据成员edge_idweight,分别用作edge_t的唯一标识符和边的权重。

我在C++中编写了tree_tsubtree_t类,它们都包含指向edge_t的指针的映射。tree_tsubtree_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对象,并且代码必须从中迭代采样subtree_t,执行一些计算,对另一个subtree_t进行采样,执行更多计算,等等。 要进行计算,代码需要知道每个子树中每个边的weightnum_descendents值。

为了避免重复计算相同的值,每次构建新的子树时,我都会创建std::map<unsigned int, unsigned int> weight_mapstd::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毫无意义。 它看起来像是尝试声明指向数据成员的指针,无论如何都不是您想要的。

最新更新