Using templates in C++ programs

In C++, you can use a template to declare and define a set of related:

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 several basic approaches to the problem of redundant instantiations:

Control implicit instantiation in the source code
To use this approach, you can use either of the following methods:
  • Concentrate implicit instantiations of a specialization

    Organize your source code so that object files contain fewer instances of each required instantiation and fewer unused instantiations. This is the least usable approach, because you must know where each template is defined and where each template instantiation is required.

  • Use explicit instantiation declarations (C++11 only)

    Support for explicit instantiation declarations can be enabled by setting the LANGLVL(EXTENDED) or LANGLVL(EXTENDED0X) compiler group suboptions. Explicit instantiation declarations give you the ability to suppress implicit instantiation of templates. This helps reduce the collective size of the object files. It may also reduce the size of the final executable if the suppressed symbol definitions are meant to be found in a shared library, or if the system linker is unable to always remove additional definitions of a symbol. This approach is described in Using explicit instantiation declarations (C++11 only).

Store instantiations in an include directory
Use the TEMPINC compiler option. If the template header and the template definition file have the required structure (described in Using the TEMPINC compiler option), 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 is the default.
Store instantiation information in a registry
Use the TEMPLATEREGISTRY 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 TEMPLATEREGISTRY compiler option provides the benefits of the TEMPINC compiler option but does not require a specific structure for the template header and the template definition file.

Note: The NOTEMPINC and TEMPLATEREGISTRY compiler options are mutually exclusive.