Templates of templates

Introduction

In this brief article we’ll have a look at the topic of building template classes whose parameters are themselves templates.

I’m assuming you’re reasonably familiar with template classes.  If not, here’s a quick introduction.

The problem

Let’s start with a case study. Suppose we want to build a simple hash table class. Our class should be generic for different types of keys and values*. Obviously, it should be a template class.

image

We might want to add more flexibility to our design by allowing the client to choose the type of container class used by the SimpleHashTable to store its keys and values (for example, for performance reasons we may want to use a fixed-size container)

We need to add the container class as a template parameter. However, a container class is typically a template class itself.

image

Let’s modify the SimpleHashTable to allow the container type to be specified:

image

We must tell the compiler that the template parameter Container_Type is itself a template class. Notice that the template parameter for the template class must not match any of the other identifiers in the template list.

The Container_Type parameter is used to instantiate a new container within the SimpleHashTable, whose template parameter is one of the template parameters supplied to the SimpleHashTable. In other words, there is a ‘cascading’ of template parameters within the class: a parameter supplied to the owning template is used to instantiate a nested template class within.

Let’s have a look at what gets created when we instantiate our SimpleHashtable class:

image

As with all template parameters, template-template parameters can be defaulted (the usual rules for defaults apply). Note, however, that the template default must be a template class.

image

Summary

Once we start building template classes it becomes natural to incorporate them into other, more complex, template classes. The aim is to build our generic code with as much flexibility as possible.

 

*This is a deliberately artificial example. You wouldn’t implement a hash table this way, typically; and you don’t need to since one is supplied with the Standard Library.

Glennan Carnie
Dislike (0)

About Glennan Carnie

Glennan is an embedded systems and software engineer with over 20 years experience, mostly in high-integrity systems for the defence and aerospace industry. He specialises in C++, UML, software modelling, Systems Engineering and process development.
This entry was posted in C/C++ Programming and tagged , , , , . Bookmark the permalink.

9 Responses to Templates of templates

  1. Pingback: C++ Template of template | Heresy's Space

  2. Pingback: Overload operator for both std::vector and std::list | Developer FAQs

Leave a Reply