我正在编写一个库来在树状对象上运行某些算法。 我有一个edge_t
类,它有const unsigned int
个数据成员edge_id
和weight
,分别用作edge_t
的唯一标识符和边的权重。
我在C++中编写了tree_t
和subtree_t
类,它们都包含指向edge_t
的指针的映射。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
对象,并且代码必须从中迭代采样subtree_t
,执行一些计算,对另一个subtree_t
进行采样,执行更多计算,等等。 要进行计算,代码需要知道每个子树中每个边的weight
和num_descendents
值。
为了避免重复计算相同的值,每次构建新的子树时,我都会创建std::map<unsigned int, unsigned int> weight_map
和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
毫无意义。 它看起来像是尝试声明指向数据成员的指针,无论如何都不是您想要的。