Generic Programming Templates
Generic Programming: Templates
Reusability and genericity Major theme in development of programming languages Reuse code to avoid repeatedly reinventing the wheel Trend contributing to this Use of generic code Can be used with different types of data Function and class templates Enable programmers to specify an entire range of related functions and related classes Generic programming
Reusability and Genericity ▪ Major theme in development of programming languages • Reuse code to avoid repeatedly reinventing the wheel ▪ Trend contributing to this • Use of generic code • Can be used with different types of data ▪ Function and class templates • Enable programmers to specify an entire range of related functions and related classes • → Generic programming 2
Function Templates (parameterized functions)
Function Templates (parameterized functions)
Motivation Initially code was reusable by encapsulating it within functions Example Write void swap (int& first, int& second) int temp= firsti first second second =temp; Then call swap(x,y);
Motivation ▪ Initially code was reusable by encapsulating it within functions ▪ Example: • Write • Then call swap(x,y); void swap (int& first, int& second) { int temp = first; first = second; second = temp; }
To swap variables of different types, write another function Overloading allows functions to have same name Signature(types and numbers of parameters) keep them unique to the compiler This could lead to a library of swap functions One function for each standard/primitive type Compiler chooses which to use from signature void swap (int& first, int& second) int temp firsti first second: second temp void swap (double& first, double& second double temp first first second void swap (char& first, char& second second temp first second second temp; But . what about swapping user defined types such as an object? We cannot cover the swap function for ALL possible class objects
▪ To swap variables of different types, write another function • Overloading allows functions to have same name • Signature (types and numbers of parameters) keep them unique to the compiler ▪ This could lead to a library of swap functions • One function for each standard/primitive type • Compiler chooses which to use from signature ▪ But … what about swapping user defined types such as an object? • We cannot cover the swap function for ALL possible class objects void swap (int& first, int& second) { int temp = first; first = second; second = temp; } void swap (double& first, double& second) { double temp = first; first = second; second = temp; } void swap (char& first, char& second) { char temp = first; first = second; second = temp; }