Algorithm function: create a template or take the std :: function parameter?

I have a C ++ class called Graph, and it has a for_each_node () algorithm method. I can either make it a template, for example:

template <class UnaryFunction> UnaryFunction Graph::for_each_node (UnaryFunction f) { /* ... */ } 

or use its std :: function, for example:

 typedef std::function<void (Node&)> ForEachNodeFunc; ForEachNodeFunc Graph::for_each_node (ForEachNodeFunc f) { /* ... */ } 

Standard algorithms, for example. std :: for_each, use the first approach, while some libraries, for example. gtkmm (which is a binding to C ++ GTK +) accepts functions as pointers to functions of objects containing them.

What are the advantages and disadvantages of each option? I'm not sure which one to choose. What should influence the choice: is my Graph class a class template, or how many different functions are supposed to be used with an algorithm method or speed requirements?

+7
source share
1 answer

Take a look at this Andy Prole answer, I think this is partly the answer to your question:

In general, if you are faced with a design situation that gives you a choice, use templates ...

stack overflow.squite

+5
source

All Articles