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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With