Skip to content

Do not use std::function in the interface #159

@akrzemi1

Description

@akrzemi1

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions