Variadic Class Templates
Gain valuable insights into variadic class templates through the implementation and analysis of a basic tuple class.
We'll cover the following...
Class templates may also have a variable number of template arguments. This is key to building some categories of types, such as tuple
and variant
, that are available in the standard library. In this lesson, we’ll see how we could write a simple implementation for a tuple
class. A tuple is a type that represents a fixed-size collection of heterogeneous values.
Implementing variadic class templates
When implementing variadic function templates, we used a recursion pattern with two overloads, one for the general case and one for ending the recursion. The same approach has to be taken with variadic class templates, except that we need to use specialization for this purpose. Next, we can see a minimal implementation for a tuple:
template <typename T, typename... Ts>struct tuple{tuple(T const& t, Ts const &... ts) : value(t), rest(ts...){ }constexpr int size() const { return 1 + rest.size(); }T value;tuple<Ts...> rest;};template <typename T>struct tuple<T>{tuple(const T& t) : value(t){ }constexpr int size() const { return 1; }T value;};
The first class is the primary template. It has two template parameters: a type template and a parameter pack. This means, at the minimum, there must be one type specified for instantiating this template. The primary template tuple has two member variables: value
of the T
type and rest
of type tuple<Ts...>
. This is an expansion of the rest of the template arguments. This means a tuple of N
...