CodeBlanks Logo Icon CodeBlanks

Template instantiation

Learn the template instantiation mechanism.

Template instantiation

Template instantiation is the compiler generating concrete code from a template. The template itself is not code; it is a recipe. For each type used, concrete code is generated.

There are two kinds: implicit — the compiler generates automatically when the template is used; explicit — the programmer forces generation with template class Foo<int>;. Explicit instantiation is used to reduce compile time and solve translation-unit boundaries.

Implicit instantiation

The template template <typename T> T identity(T x) { return x; } generates no code when declared. When identity(7) is first called, the compiler generates the identity<int> version.

If called with a second type (identity(3.14)), the compiler generates identity<double>. So a separate concrete function is generated for each distinct type. This is why templates must be fully in a header; otherwise the compiler cannot see uses in other translation units.

Practice Write the identity template

Write template <typename T> T identity(T x) with body return x;. In main write std::cout << identity(7);.

Starter code

main.cpp
#include <iostream>

// Define the identity template function here

int main() {
    // Call identity and print it
    return 0;
}

Sample solution

main.cpp
#include <iostream>

template <typename T>
T identity(T x) {
    return x;
}

int main() {
    std::cout << identity(7);
    return 0;
}

Expected output

7

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match each concept to its role

Term Meaning
implicit instantiation Automatic at use site
explicit instantiation template class Foo<int>;
type deduction auto x = ...
specialization Special behavior

2 Complete the explicit instantiation

Question
template ____ Vector<int>;
Answer
template class Vector<int>;

Explanation: template class Vector<int>; declares explicit instantiation.

3 When does implicit template instantiation happen?

main.cpp
template <typename T> T identity(T x) { return x; }
auto a = identity(7);
  • When the compiler sees the template
  • During linking
  • When the template is used (called) Correct answer
  • At run time

Explanation: In implicit instantiation, code is generated when the template is first used.

All lessons in Expert