是的,您可以通过多种方式做到这一点。这里有两种常见的可能性。
旧式函数指针
class mytree
{
// typedef for a function pointer to act
typedef void (*node_fn_ptr)(tree_node&);
void in_order(node_fn_ptr)
{
tree_node* pNode;
while (/* ... */)
{
// traverse...
// ... lots of code
// found node!
(*fnptr)(*pNode);
// equivalently: fnptr(*pNode)
}
}
};
void MyFunc(tree_node& tn)
{
// ...
}
void sample(mytree& tree)
{
// called with a default constructed function:
tree.inorder(&MyFunc);
// equivalently: tree.inorder(MyFunc);
}
使用函子
使用模板成员,使用函数指针
class mytree
{
// typedef for a function pointer to act
typedef void (*node_fn_ptr)(tree_node&);
template<class F>
void in_order(F f)
{
tree_node* pNode;
while (/* ... */)
{
// traverse...
// ... lots of code
// found node!
f(*pNode);
}
}
};
struct ExampleFunctor
{
void operator()(tree_node& node)
{
// do something with node
}
}
void sample(mytree& tree)
{
// called with a default constructed function:
tree.inorder(ExampleFunctor());
}