Templates are of great utility to programmers in C++, especially when combined with multiple inheritance and operator overloading. The C++ Standard Template Library (STL) provides many useful functions within a framework of connected templates.

As the templates in C++ are very expressive they may be used for things other than generic programming. One such use is called template metaprogramming, which is a way of pre-evaluating some of the code at compile-time rather than run-time. Further discussion here only relates to templates as a method of generic programming.

Table of Contents

Understanding Function Templates

Let’s start with function templates, which act like functions that can handle various data types. For instance, consider the max function template in the C++ Standard Template Library (STL). It determines the larger of two values, regardless of their types. The max() could be defined like this:

This template works with different types, and you can use it just like a regular function:

cout << max(3, 7); // outputs 7 

The compiler determines by examining the arguments that this is a call to max(int, int) and instantiates a version of the function where the type T is int.

There are three primary challenges to the use of templates.

  1. Some C++ compilers historically lack good template support, impacting code portability.
  2. Error messages in template code can be confusing and unhelpful, making development challenging.
  3. Indiscriminate template usage may lead to code bloat, resulting in excessively large executables.

The Role of the typename Keyword

The typename keyword plays a crucial role in avoiding confusion when working with templates. For instance:

The template definition assumes that the C++ class T that you hand it must have a nested identifier of some kind called id. But id could be a member object of T, in which case you can perform operations on id directly, but you couldn’t create an object of the type id. However, that’s exactly what is happening here: the identifier id is being treated as if it were actually a nested type inside T. In the case of class Y, id is in fact a nested type, but (without the typename keyword) the compiler can’t know that when it’s compiling X.

If, when it sees an identifier in a template, the compiler has the option of treating that identifier as a type or as something other than a type, then it will assume that the identifier refers to something other than a type. That is, it will assume that the identifier refers to an object (including variables of primitive types), an enumeration or something similar. However, it will not just assume that it is a type. Thus, the compiler gets confused when we pretend it’s a type.

Because the default behavior of the compiler is to assume that a name that fits the above two points is not a type, you must use typename for nested names, even in places where you think that the compiler ought to be able to figure out the right way to interpret the name on its own. In the above example, when the compiler sees T::id, it knows (because of the typename keyword) that id refers to a nested type and thus it can create an object of that type.

The short version of the rule is: if your type is qualified by a template type parameter, you must use typename.

Typedefing a typename

The typename keyword does not automatically create a typedef. A line which reads: typename Seq::iterator It;

causes a variable to be declared of type Seq::iterator. If you mean to make a typedef, you must say: typedef typename Seq::iterator It;

Using typename instead of class

With the introduction of the typename keyword, you now have the option of using typename instead of class in the template argument list of a template definition. This may produce code which is clearer. You can use ‘typename’ in the template argument list as below:

You’ll probably see a great deal of code which does not use typename in this fashion, since the keyword was added to the language a relatively long time after templates were introduced.

Function Templates

A class template describes an infinite set of classes, and the most common place you’ll see templates is with classes. However, C++ also supports the concept of an infinite set of functions, which is sometimes useful. The syntax is virtually identical, except that you create a function instead of a class.

The clue that you should create a function template is, as you might suspect, if you find you’re creating a number of functions that look identical except that they are dealing with different types. The classic example of a function template is a sorting function. However, a function template is useful in all sorts of places, as demonstrated in the first example that follows. The second example shows a function template used with containers and iterators.

Here’s a test program, that includes the use of the Standard Library complex number type by using the previous code.

The output of this C++ program is:

Type Induction in Function Templates

As a simple but very useful example, consider the following:

This actually figures out the size of an array as a compile-time constant value, without using any sizeof( ) operations! Thus you can have a much more succinct way to calculate the size of an array at compile time:

Of course, just making a variable of a built-in type a const does not guarantee it’s actually a compile-time constant, but if it’s used to define the size of an array (as it is in the last line of main( )), then it must be a compile-time constant.

Taking the address of a generated function template

There are a number of situations where you need to take the address of a function. For example, you may have a function that takes an argument of a pointer to another function. Of course it’s possible that this other function might be generated from a template function so you need some way to take that kind of address :

This example demonstrates a number of different issues. First, even though you’re using templates, the signatures must match the function h( ) takes a pointer to a function that takes an int* and returns void, and that’s what the template f produces. Second, the function that wants the function pointer as an argument can itself be a template, as in the case of the template g.

In main( ) you can see that type induction works here, too. The first call to h( ) explicitly gives the template argument for f, but since h( ) says that it will only take the address of a function that takes an int*, that part can be induced by the compiler. With g( ) the situation is even more interesting because there are two templates involved. The compiler cannot induce the type with nothing to go on, but if either f or g is given int, then the rest can be induced.

Member Function Templates

It’s also possible to make apply( ) a member function template of the class. That is, a separate template definition from the class template, and yet a member of the class. This may produce a cleaner syntax:

The definition of the apply( ) functions turn out to be cleaner, as well, because they are members of the container. To accomplish this, a new container is inherited from one of the existing STL sequence containers and the member function templates are added to the new type. However, for maximum flexibility we’d like to be able to use any of the STL sequence containers, and for this to work a template-template must be used, to tell the compiler that a template argument is actually a template, itself, and can thus take a type argument and be instantiated. Here is what it looks like after bringing the apply( ) functions into the new type as member functions:

Because they are members, the apply( ) functions don’t need as many arguments, and the iterator class doesn’t need to be qualified. Also, begin( ) and end( ) are now member functions of the new type and so look cleaner as well. However, the basic code is still the same.

You can see how the function calls are also simpler for the client programmer:

Conceptually, it reads more sensibly to say that you’re calling apply( ) for the dogs container.

Template bloating

Template bloating in C++ refers to the phenomenon where the use of templates leads to the generation of excessive and redundant code during compilation. This can result in larger executable files, increased compilation times, and challenges for debuggers. Template bloat occurs when the compiler generates multiple copies (instantiations) of template code for different template parameters, even if the functionality remains the same.

Causes of Template Bloating:

  1. Compiler Generates Code for Each Instantiation:
    • Every time a template is used with different type parameters, the compiler generates a new copy of the template code for each instantiation.
    • This can lead to redundancy when the template’s logic remains consistent across different types.
  2. Debuggers and Breakpoints:
    • Debugging template-heavy code can be challenging as breakpoints may be set within the template, causing debuggers to struggle with handling multiple instantiations.

As before, the inline functions generate no code and are thus “free.” The functionality is provided by creating the base-class code only once. However, the ownership problem has been solved here by adding a destructor (which is type-dependent, and thus must be created by the template). Here, it defaults to ownership. Notice that when the base-class destructor is called, the stack will be empty so no duplicate releases will occur.

Preventing Template Bloating

Use Explicit instantiation

At times it is useful to explicitly instantiate a template; that is, to tell the compiler to lay down the code for a specific version of that template even though you’re not creating an object at that point. To do this, you reuse the template keyword as follows:

In this example, the explicit instantiation doesn’t really accomplish anything; the program would work the same without it. Explicit instantiation is only for special cases where extra control is needed. Here is a complete source code of templates in C++.

Put Non-Type-Dependent Functionality in a Base Class:

If parts of the template code are not type-dependent, place them in a common base class to avoid redundant code generation.