Compiling Templates

Like an ordinary function, a function template requires a definition before the function can be called. Like an ordinary class, a class template requires a definition for each member function and static data member before they can be used. Unlike ordinary functions or members, however, templates are typically defined in every source file.

Templates are often used by placing a template declaration and all supporting definitions in a header file, (e.g., template.h). Then #include that file anywhere the template is needed. For every implicit or explicit instantiation, the compiler generates the necessary code for the template’s instantiation. If multiple source files instantiate the same template with the same arguments, the compiler and linker ensure that the program contains a single copy of the instantiated functions and members.

Different compilers use different techniques to ensure that the program contains a single copy of each template instance. The following are four different approaches:

  • The most common approach is to have the compiler keep track of which source files require which instantiations. When the program is linked, the compiler combines all the lists of required instantiations and compiles the template instantiations at that time. As an optimization, the compiler saves the compiled instantiations, so an instantiation that does not change does not need to be recompiled.

  • Another approach is to have the compiler generate the code for all needed instantiations ...

Get C++ In a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.