首页 > 解决方案 > 如何通过函数指针递归调用类成员函数?

问题描述

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

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

为了避免重复计算相同的值,每次我构建一个新的子树时,我都会创建std::map<unsigned int, unsigned int> weight_mapand 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是什么?

标签: c++recursionmember-function-pointers

解决方案


f已经是指向所需成员的指针,所以只需传递:

populate_map(S, c, m, f);

&basic_tree_t::*f在这种情况下没有任何意义。它看起来像是试图声明一个指向数据成员的指针,这无论如何都不是你想要的。


推荐阅读