Tag Dispatching
Learn about tag dispatching techniques, and instantiate specific overloads.
We'll cover the following...
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);
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 ofn
times.For bidirectional iterators, it could call either
operator++
a number ofn
times (ifn
is a positive number) oroperator--
a number ofn
times (ifn
is a negative number).For random-access iterators, it can use the
operator+=
to increment it directly withn
elements.
This implies there can be three different ...