0% found this document useful (0 votes)
15 views

Introduction To Programming - CS201 Power Point Slides Lecture 41

Uploaded by

Hasnain ullah
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Introduction To Programming - CS201 Power Point Slides Lecture 41

Uploaded by

Hasnain ullah
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 30

Introduction to

Programming
Lecture 41
Template
s
Types of
Templates
 Function Template
 Class Templates
Swap Function
void swap ( int & i , int & j )
{
int temp ;
temp = i ;
i=j;
j = temp ;
}
Function
Overloadin
g
Function
Templates
template < class T
>
return_type function_name ( argument_list
argument_lis
)
Example
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 ) ;
}
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 ) ;
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 ) ;
inverse ( i ) ;
}
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 ) ;
}
main ( )
Example
{
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 ) ;
}
main ( )
Example
{
PhoneCall a ( 10 , ‘S’ ) ;
a.display ( ) ;
a = reverse ( a ) ;
a.display ( ) ;
}

You might also like