Template Instantiation In and of itself, the template does nothing When the compiler encounters a template it stores the template but doesnt generate any machine instructions or codes When a function template is instantiated Compiler finds type parameters in list of function template For each type in the function parameter list, type of corresponding argument is determined These two function type and argument type are then bound together E.g., when it encounters a call to swap ( EXample: swap(int, int)i it generates an integer instance of swap() The type will be determined by the compiler (at compilation time from the type of the arguments passed when swap() is called Cannot specify plata type at run time Static binding!
Template Instantiation ▪ In and of itself, the template does nothing ▪ When the compiler encounters a template • it stores the template • but doesn't generate any machine instructions or codes ▪ When a function template is instantiated • Compiler finds type parameters in list of function template • For each type in the function parameter list, type of corresponding argument is determined • These two function type and argument type are then bound together ▪ E.g., when it encounters a call to swap() • Example: swap(int, int); • it generates an integer instance of swap() ▪ The type will be determined … • by the compiler (at compilation time) • from the type of the arguments passed when swap() is called ▪ Cannot specify data type at run time! Static binding!
Example: displayarray cpp template <typename T> void display (t array [l, int num)i for (int i =0; i num; i+ cout array[i] < i cout < endl oub1ex[]={1.1,2 display <double> created display(x, 5)i int num[]={1,2,3,4}; display(num, 4)i display<int> created 1.12.23.34.45.5 1234 Function-template specializations are generated automatically by the compiler to handle each type of call to the function template If an array of user-defined objects is used, need to overload < operator of the object class
Example: displayarray.cpp ▪ Function-template specializations are generated automatically by the compiler to handle each type of call to the function template ▪ If an array of user-defined objects is used, need to overload << operator of the object class. template <typename T> void display(T array[], int num) { for (int i = 0; i < num; i++) cout << array[i] << " "; cout << endl; } int main() { double x[] = {1.1, 2.2, 3.3, 4.4, 5.5}; display(x, 5); int num[] = {1, 2, 3, 4}; display(num, 4); } 1.1 2.2 3.3 4.4 5.5 1 2 3 4 display<double> created display<int> created