From template call to machine code

A C++ source file defines template < typename T > T scale(T x, T k) { return x * k; } and later calls scale(2.5, 4.0). Put the events that turn this call into running code in the order in which they happen during compilation and linking.

  1. 1.

    Template argument deduction sets T to double from the types of the arguments.

  2. 2.

    The instantiation is type-checked, including that double supports multiplication, and compiled to machine code.

  3. 3.

    The compiler parses the template definition and checks only the parts that do not depend on T.

  4. 4.

    The compiler substitutes double for T to form the instantiation of scale for double.

  5. 5.

    The compiler reaches the call to scale with two double arguments.

  6. 6.

    The linker keeps a single copy of the double instantiation when several object files contain it.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Generics Questions: