C++:将函数作为参数传递给另一个函数 [英] c++: pass function as parameter to another function

查看:52
本文介绍了C++:将函数作为参数传递给另一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在用 C++ 实现一棵二叉树,我想用一个名为 in_order() 的函数遍历它.

i am currently implementing a binary tree in c++ and i want to traverse it with a function called in_order().

有什么方法可以将函数作为参数传递,以便我可以执行以下操作(无需编写代码来多次遍历列表)?

is there any way to pass a function as an argument, so that i can do things like below (without having to write the code to traverse the list more than once)?

struct tree_node; // and so on
class  tree;      // and so on

void print_node () {
  // some stuff here
}

// some other functions

tree mytree();

// insert some nodes

mytree.in_order(print_node);
mytree.in_order(push_node_to_stack);
mytree.in_order(something_else);

推荐答案

是的,您可以通过多种方式做到这一点.这里有两种常见的可能性.

Yes, you can do this in a number of ways. Here are two common possibilities.

旧式函数指针

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);
}

使用函子

使用模板成员,使用函数指针

With a template member, works with function pointers

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());
}

这篇关于C++:将函数作为参数传递给另一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆