Understanding Template Instantiation

Gain a deep understanding of template instantiation in this lesson.

As mentioned before, templates are only blueprints from which the compiler creates actual code when it encounters their use. The act of creating a definition for a function, a class, or a variable from the template declaration is called template instantiation. This can be either explicit, when we tell the compiler when it should generate a definition, or implicit, when the compiler generates a new definition as needed. We’ll look at these two forms in detail in this lesson.

Implicit instantiation

Implicit instantiation occurs when the compiler generates definitions based on the use of templates and when no explicit instantiation is present. Implicitly instantiated templates are defined in the same namespace as the template. However, the way compilers create definitions from templates may differ. This is something we will see in the following example. Let’s consider this code:

Get hands-on with 1200+ tech skills courses.