graph-v2 icon indicating copy to clipboard operation
graph-v2 copied to clipboard

Do not use `std::function` in the interface

Open akrzemi1 opened this issue 6 months ago • 1 comments

dijkstra_shortest_distances, unless explicitly overridden, uses std::function to store the weight function. This is not desirable. An allocating, type-erasing type for a callback goes against the generic library design.

The idea behind using the templated algorithms is that the instantiated code is as efficient as if you typed it by hand. This gets compromised when you start using dynamic type erasure as the one used by std::function.

Instead, I would recommend doing one of the following:

  1. Provide two overloads: one without the weight function, the other deducing the type of the eight function from the function argument.
  2. Define a helper class for returning the value "one" in a given type, and use this as a default:
template <numeric T>
class one
{
public:
  template <class U>
  T operator()(U&&) const { return T(1); }
};
template </*...*/
          class WF  = one<range_value_t<Distances>>,
          /*...*/>
constexpr void dijkstra_shortest_distances(/*...*/
                                           WF&& weight  = {}, 
                                           /*...*/);

The Standard Library appears to be following the second approach: https://eel.is/c++draft/alg.any.of

akrzemi1 avatar Jun 06 '25 11:06 akrzemi1

Note that you also use a similar function for returning "infinity" for any numeric type.

akrzemi1 avatar Jun 06 '25 11:06 akrzemi1