Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm function: Make it a template or take a std::function parameter? [duplicate]

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

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

or make it use std::function, like this:

typedef std::function<void (Node&)> ForEachNodeFunc;

ForEachNodeFunc Graph::for_each_node (ForEachNodeFunc f)
{
     /* ... */
}

Standard algorithms, e.g. std::for_each, use the first approach, while some libraries, e.g. gtkmm (which is the C++ binding of GTK+), take functions as function pointers of objects containing them.

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

like image 765
cfa45ca55111016ee9269f0a52e771 Avatar asked Feb 24 '13 10:02

cfa45ca55111016ee9269f0a52e771


1 Answers

Take a look at this answer by Andy Prowl, I think it is partially the answer on your question as well:

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

https://stackoverflow.com/a/14678298/1758762 (std::function vs template)

like image 177
Leo Chapiro Avatar answered Sep 30 '22 22:09

Leo Chapiro