I have created a very simple Tree implementation, and I would like to be able to pass a function object to my traverse() function. e.g.
template<class T>
class MyTree
{
public:
void traverse(MyFunction f) {
traverse(root, f);
}
private:
MyTreeNode<T>* root;
void traverse(MyTreeNode<T>*, MyFunction f);
};
The thing is, how do I declare f if I want to pass in some parameters as well as the node in question? ( pointers to other structs ). Alternatively, can anyone point me in the direction of some tutorials?
There are different things that you can do at this stage.
The old style C type solution: you can pass a function pointer:
That will take as argument a function pointer (free function) that takes a pointer to a
MyTreeNode<T>object as first argument and an integer as second argument. And you cantypedefthe function type to ease usage:You can take any callable thing as argument with the help of a template:
Which in the simplest approach is simple if you leave the argument types free, but the error messages if you try to pass a callable entity that takes a different set of arguments may not be so simple to parse. Internally you can use
fas if it were a function, but externally can be either a function or function objects, including the result ofstd::bind(c++0x) orboost::bindYou can go one step forward and actually enforce in the signature of the
traversefunction the arguments you are going to use by usingstd::function(again, c++0x) orboost::function:The advantage of this solution is that it is clear how you are going to use the passed in parameter (as in the function pointer approach): you will call
f( x, y )wherexis aMyTreeNode<T>*andyis an integer. At the same time you provide the genericity of the templated solution by means ofstd::bind(c++0x) orboost::bind, that can be used to adapt different entities to thefunction<...>argument, including free functions, function objects, member functions…