Introduction to Programming Lecture 41
Templates
Types of Templates Function Templates Class Templates
Swap Function { int temp ; temp = i ; i = j ; j = temp ; } void swap ( int & i , int & j ) { int temp ; temp = i ; i = j ; j = temp ; }
Function Overloading
Function Templates
template < class T >
return_type function_name ( argument_list )
Example int reverse ( int x ) { return ( - x ) ; } double reverse ( double x )
Example template < class T > T reverse ( T x ) { return (- x ) ; }
Example main ( ) { int i ; ……. reverse ( i ) ; }
Example main ( ) { int i ; … reverse ( i ) ; double y ; reverse ( y ) ; }
Code Reuse
Example template < class T > void swap ( T & x , T & y ) { T temp ; temp = x ; x = y ; y = temp ; }
int a , b ; char a , b ; swap ( a , b ) ;
Example template < class T > void swap ( T & x , T & y ) { T temp ; temp = x ; x = y ; y = temp ; }
template < class T , class U >
Example template <class T> T larger ( T x, T y ) { T big ; if ( x > y ) big = x ; else big = y ; return ( big ) ; }
Example main ( ) { int i = 5 , j = 7 ; double x = 10.0 , y = 15.0 ; cout << larger ( i , j ) << endl ; cout << larger ( x , y ) << endl ; // cout << larger ( i , y ) ; Error }
Example template <class T> void inverse ( T & x , T & y ) { T temp ; temp = x ; x = y ; y = temp ; }
Example template <class T> T inverse ( T x ) { return ( - x ) ; }
Example main ( ) { int i = 4 , j = 8 ; inverse ( i , j ) ; }
Example template <class T> T reverse ( T x ) { return ( - x ) ; } void main ( ) double a = 10.75 ; reverse ( a ) ; reverse <int> ( a ) ;
Example template <class T , class U> T reverse ( U x ) { return ( - x ) ; }
Example main ( ) { double a = 8.8 ; reverse ( a ) ; reverse <int> ( a ) ; reverse <int , double> ( a ) ; reverse<double , double> ( a ) ; reverse<double , int> ( a ) ; }
Example class PhoneCall { private : int lengthOfCall ; char billCode ; public : PhoneCall ( const int i , char b ) ; PhoneCall ( PoneCall & p ) ; PhoneCall PhoneCall :: operator - ( void ) ; void display ( void ) ; } ;
Example template <class T> T reverse ( T x ) { return ( - x ) ; }
Example PhoneCall reverse ( PhoneCall x ) { return (- x ) ; }
Example PhoneCall PhoneCall :: operator - ( void ) { PhoneCall temp ( * this ) ; temp.billCode = 'C' ; return ( temp ) ; }
Example main ( ) { PhoneCall a ( 10 , ‘S’ ) ; a.display ( ) ; a = reverse ( a ) ; }