Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantages of tag dispatching over normal overload resolution

Plain and simple: what's the advantage of tag dispatching over normal overload resolution?

These are both compile-time processes right? So there shouldn't be a 'performance winner' I suppose. And every tag dispatching case should be able, to some extent, to be rewritten/refactored into normal overloading (possibly by adding multiple types), right?

Aside from the different way of working and selecting candidates, why should I prefer tag dispatching over overload resolution and in which cases?

like image 273
Dean Avatar asked Jul 27 '16 21:07

Dean


2 Answers

Tag dispatching is basically a name given to a technique employed to find correct overloaded function. So, technically it is nothing but overloading only.

To put it from Boost site:

Tag dispatching is a way of using function overloading to dispatch based on properties of a type, and is often used hand in hand with traits classes.

You can see it used all over in you standard library algorithm header file. Just for the sake of an example, consider that there is an algorithm AlgoX which can be performed a lot more efficiently on a container providing random access (eg vector) than a container providing bidirectional access (list). So, for selecting the algorithm based on the iterator type one would use tag dispatching using iterator_traits

template <typename Iter>
void AlgoXImpl(Iter first, Iter last, bidirectional_iterator_tag) {
  //.....Algo specialized to bidirectional iterators
}

template <typename Iter>
void AlgoXImpl(Iter first, Iter last, random_access_iterator_tag) {
  //.....Algo specialized to random access iterators
}

template <typename Iter>
void AlgoX(Iter first, Iter last) {
  if (first == last) return;
  AlgoXImpl(first, last, typename iterator_traits<Iter>::iterator_category());
}

As you can see, to a simple mind this is nothing but an example of operator overloading as the categories are essentially different types.

For a more real world example, you can checkout out how std::rotate is implemented.

like image 132
Arunmu Avatar answered Nov 20 '22 16:11

Arunmu


Tags can be associated with a type, even including basic primitive types, through appropriate trait classes. E.g., it would be impossible to make a pointer type a subclass of some iterator concept. However, a templated trait class may associate it with the desired tag. Thus, tag-based dispatching adds flexibility that allows to build a dispatch scheme that must not already be defined by the involved types.

like image 2
Thomas B Preusser Avatar answered Nov 20 '22 17:11

Thomas B Preusser