Using C++ templates
In C++, you can use a template to declare a set of related:
- Classes (including structures)
- Functions
- Static data members of template classes
Within an application, you can instantiate the same template multiple times
with the same arguments or with different arguments. If you use the same arguments,
the repeated instantiations are redundant. These redundant instantiations
increase compilation time, increase the size of the executable, and deliver
no benefit.
There are four basic approaches to the problem of redundant instantiations:
- Code for unique instantiations
- Organize your source code so that the object files contain only one
instance of each required instantiation and no unused instantiations. This
is the least usable approach, because you must know where each template is
defined and where each template instantiation is required.
- Instantiate at every occurrence
- Use the -qnotempinc and -qnotemplateregistry compiler options (these are the default settings).
The compiler generates code for every instantiation that it encounters. With
this approach, you accept the disadvantages of redundant instantiations.
- Have the compiler store instantiations in a template include
directory
- Use the -qtempinc compiler option. If the
template definition and implementation files have the required structure,
each template instantiation is stored in a template include directory. If
the compiler is asked to instantiate the same template again with the same
arguments, it uses the stored version instead. This approach is described
in Using the -qtempinc compiler option.
- Have the compiler store instantiation information in a registry
- Use the -qtemplateregistry compiler option.
Information about each template instantiation is stored in a template registry.
If the compiler is asked to instantiate the same template again with the same
arguments, it points to the instantiation in the first object file instead.
The -qtemplateregistry compiler option provides
the benefits of the -qtempinc compiler option
but does not require a specific structure for the template definition and
implementation files. This approach is described in Using the -qtemplateregistry compiler option.
Note:
The -qtempinc and -qtemplateregistry compiler options are mutually exclusive.