I am new to using algorithmand functionalin C ++. I need to do a tree traversal and execute a function for each element. See code below.
It works, but I have a few things that I don't like, and maybe they can do better. Please note that I am limited to the rather old version of g ++ (4.4.7) and cannot use lambda functions.
I use a wrapper function do_walkand std::bindto call a member function walkfor each element. Is there a way to avoid a wrapper function and directly call a member function?
I am using typedef for a callback function UnaryFunction. I would rather use the template version walk. However, when I change the code to use the template, I get the following compilation error: error: no matching function for call to 'bind(<unresolved overloaded function type>, std::_Placeholder<1>&, void (*&)(const Elem&))'. Can templates be used in this context?
Perhaps there is an alternative std::for_eachthat is better suited for this kind of tree traversal?
My code is:
#include <list>
#include <algorithm>
#include <functional>
struct Elem;
typedef void (*UnaryFunction)(const Elem&);
struct Elem
{
std::list<Elem> children;
void walk(UnaryFunction f) const
{
std::for_each(
children.begin(),
children.end(),
std::bind(do_walk, std::placeholders::_1, f));
f(*this);
}
static void do_walk(const Elem& elem, UnaryFunction f)
{
elem.walk(f);
}
};
void pretty_print(const Elem& elem)
{
}
int main()
{
Elem root;
root.walk(pretty_print);
return 0;
}
source
share