c++: pass function as parameter to another function

此生再无相见时 提交于 2019-12-04 09:54:17

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

Old-style function pointers

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

Using functors

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

Yes, you can use a function pointer as a parameter to in_order. You may also need to overload it, in case the passed functions' signatures don't match. For functions like print_node, declare in_order like this (provided its return type is void as well):

void tree::in_order( void (*)() )
{
   //implementation
}

I think you should use the visitor pattern instead.

http://en.wikipedia.org/wiki/Visitor_pattern

The base visitor class should have a virtual method to operate on a node. Pass the visitor as an argument to your in_order method. Then derive your visitor as many times as you want for any operation you want to do.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!