...

/

Tag Dispatching

Tag Dispatching

Learn about tag dispatching techniques, and instantiate specific overloads.

Tag dispatching is a technique that enables us to select one or another function overload at compile time. It’s an alternative to std::enable_if and SFINAE and is simple to understand and use. The term “tag” describes an empty class that has no members (data), or functions (behavior). Such a class is only used to define a parameter (usually the last) of a function to decide whether to select it at compile-time, depending on the supplied arguments. To better understand this, let’s consider an example.

The standard library contains a utility function called std::advance that looks as follows:

template<typename InputIt, typename Distance>
void advance(InputIt& it, Distance n);
Declaration of the std::advance utility function

Notice that in C++17, this is also constexpr (more about this, shortly). This function increments the given iterator by n elements. However, there are several categories of iterators (input, output, forward, bidirectional, and random access). That means such an operation can be computed differently:

  • For input iterators, it could call operator++ a number of n times.

  • For bidirectional iterators, it could call either operator++ a number of n times (if n is a positive number) or operator-- a number of n times (if n is a negative number).

  • For random-access iterators, it can use the operator+= to increment it directly with n elements.

This implies there can be three different ...