Template template parameters

This is actually not a typo, I really meant to repeat the first word. Let’s see what template template parameters are..

Suppose we have the following definitions:

template <typename T> struct vector;
template <typename T> struct list;

What we would like to do is, write a generic implementation of a set. Our Set implementation should support a generic type T, and any proper container data-structure (such as list, or vector). How would we do it? Here’s what we can do with a template template parameter:

template <
    typename T,
    template <typename> class Container
>
class Set {
    Container<T> data_;
    // ...
};

// usage:
Set<int, list> set1;
Set<float, vector> set2;

Container is a template name of a templated class with one typename parameter. This parameter can be named but can’t be used (you can name it only for the sole purpose of improving readability, much like using class/typename with regular templates), like so:

template <
    typename T,
    template <typename ContainerDataType> class Container
>
struct Deque;

I suggest to simply think of this mechanism as another available type to be templated on; Previously we had “typename”/”class” (along with compile-time constant types, like int) at our disposal, and now “template” has been added to the arsenal. Providing:

template <typename/class/template ...> struct A;

You are most welcome to visit this link for a few examples illustrating some use cases for template template arguments along with template specialization, or this link for a more straightforward example.

Leave a Reply