Lesson 157 +10 XP

Template Instantiation

Template Instantiation

Turning a template into a real, typed function is called template instantiation. For every concrete type the code uses, the compiler instantiates a specialized version.

A separate version per type

max(3, 8);        // instantiates an int version of max
max(2.5, 1.5);    // instantiates a double version of max

The int call and the double call each trigger their own code with the correct type substituted. Types you never use get no version at all.

Happens at compile time

using namespace std;

int main() {
  cout << max(3, 8) << "\n";
  return 0;
}

Instantiation happens while the code is being compiled. By the time the program runs, each version is finished machine code - the templating is already done.

Zero runtime cost

Because the compiler does the work up front, using a template adds no runtime cost. The generated int version runs just as fast as one you had written by hand.

Different types, different functions

max(int) and max(double) are different functions, even though both came from the same template. Each specialization stays fully separate.

TL;DR

  • Instantiation produces a concrete function for each type used.
  • It happens at compile time, not runtime.
  • Each type gets its own specialized copy.
  • Templates add zero runtime cost; the compiler does the work up front.