在调用传递给模板函数的函数时调用指向成员的函数

Rob*_*all 1 c++ templates pointers function-pointers argument-passing

这是我正在尝试使用的提供的函数模板:

template <class Process, class BTNode>
void postorder(Process f, BTNode* node_ptr)
{
   if (node_ptr != 0)
   {
      postorder( f, node_ptr->left() );
      postorder( f, node_ptr->right() );
      f( node_ptr->data() );
   }
}
Run Code Online (Sandbox Code Playgroud)

这是我的电话,我正在传递的功能:

void city_db::print_bst() {
   postorder(&city_db::print, head);
}

void city_db::print(city_record target)
{
   std::cout << target.get_code();
}
Run Code Online (Sandbox Code Playgroud)

这是我得到的编译时间(G ++)错误:

CityDb.cpp:85:从这里实例化

BinTree.template:80:错误:必须使用'.'或' - > '在'f(...)'中调用指向成员的函数

make:***[CityDb.o]错误1

这是参考f( node_ptr->data() );功能模板中的行.

这适用于Data Structures项目.赋值被修改,所以我们不需要将函数传递给函数,但是我已经对它感兴趣了很长一段时间,我觉得我差点把它放在这里.我已经筋疲力尽了谷歌和实验室TA,所以如果StackOverflow有想法,他们将不胜感激.

Tho*_*mas 7

你的问题是postorder接受一个必须以这种方式调用的函数对象:

f(arg);
Run Code Online (Sandbox Code Playgroud)

您正在传递指向成员函数的指针.您应该首先调用mem_fun从指向成员的指针创建一个函数对象:

std::mem_fun(&city_db::print)
Run Code Online (Sandbox Code Playgroud)

返回的函数对象有两个参数:指向city_db(隐式this指针)的指针和要打印的对象.您可以使用bind1st将第一个绑定到此,如下所示:

std::bind1st(std::mem_fun(&city_db::print), this)
Run Code Online (Sandbox Code Playgroud)

现在你应该可以在上面调用postorder:

postorder(std::bind1st(std::mem_fun(&city_db::print), this), head);
Run Code Online (Sandbox Code Playgroud)