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.
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.
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.
Let’s modify the SimpleHashTable to allow the container type to be specified:
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:
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.
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.