CS201-41 - Introduction to Programming Lecture 41 Templates...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Introduction to Programming Lecture 41 Templates Types of Templates Function Templates Class Templates void swap ( int & i , int & j ) Swap Function { } int temp ; temp = i ; i = j ; j = temp ; Function Overloading Function Templates template < class T > return_type function_name ( argument_list ) int reverse ( int x ) { return ( ­ x ) ; } double reverse ( double x ) { return ( ­ 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 ) ; } Example Code Reuse Example template < class T > 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 ) ; template < class T > void swap ( T & x , T & y ) { T temp ; temp = x ; x = y ; y = temp ; } Example 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 ) ; } 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 ) ; inverse ( i ) ; } Example Example template <class T> T reverse ( T x ) { return ( ­ x ) ; } void main ( ) { double a = 10.75 ; reverse ( a ) ; reverse <int> ( a ) ; } 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 Example PhoneCall reverse ( PhoneCall x ) { return (­ x ) ; } Example PhoneCall PhoneCall :: operator ­ ( void ) { PhoneCall temp ( * this ) ; temp.billCode = 'C' ; return ( temp ) ; } main ( ) { PhoneCall a ( 10 , ‘S’ ) ; a.display ( ) ; a = reverse ( a ) ; a.display ( ) ; } Example ...
View Full Document

Ask a homework question - tutors are online