Preventing template bloat

Each time you instantiate a template, the code in the template is generated anew (except for inline functions). If some of the functionality of a template does not depend on type, it can be put in a common base class to prevent needless reproduction of that code.

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.

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:

Here is a version of the Sorted.cpp example that explicitly instantiates a template before using it:

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.

Share
Tweet
Share
Pin