Templates
Templates
es
ClO-3, PLO2, C3
Templates
• Function Templates
• Class Templates
Templates
Function
Templates
Function Templates
x=5
template <class cse>
y = 10
void sqr(cse a)
The Square of 5
{
cse result; is 25
result= a * a; The Square of 10
cout << "\n The Square of " <<a is 100
<< " is " << result ; The Square of 0.2
} is 0.04
int main() The Square of 0.3
{
is 0.09
int x = 5, y = 10;
float m = 0.2, n = 0.3; void sqr(int a)
{
cout << "\nx = " << x << int result;
"\ny = " << y; result= a * a;
sqr(x); cout << "\n The Square of " <<a << " is
" << result ; }
sqr(y);
sqr(m);
sqr(n); }
Function Templates
display ( x , y );
display ( x , m );
display ( n , asad );
}
Function Templates
…..
public:
… ..
};
Class Templates
template <class A>
class item {
private:
A weight;
A price; Output
public:
indata() { cin>>weight; cin>>price; }
showdata(){cout<<"weight " <<weight; cout<< "
334.55
price= \n" << price; }
};
weight 334 price=0
main( ) {
item<int> book; weight 4.2039e-045 price=0
item<float> pen;
book.indata();
book.showdata();
pen.indata();
pen.showdata();
Class Templates
template <class a, class b>
class item
{ private:
a id;
b price;
public: Output
indata(a one, b two) { id= one; price=two; }
showdata(){cout<<"\n id = " <<id; cout<< "
price= " << price; }
}; id = 4 price= 44
id = 8.5 price=
main( )
{ 77.9
item <int, int>book; item <float, float>pen;
book.indata(4,44); book.showdata();
pen.indata(8.5,77.9); pen.showdata();
}
Class Templates
template <class a, class b>
class item
{ private:
a id;
b price;
public:
indata(a one, b two) { id= one; price=two; }
showdata(){cout<<"\n id = " <<id; cout<< " price=
" << price; }
}; Output
main( ) {
item <int, int>book; item <float, float>pen;
item <float, int>pencil; id = 4 price= 44
book.indata(4,44);
book.showdata(); id = 8.5 price= 77.9
pen.indata(8.5,77.9);
pen.showdata();
pencil.indata(1.11, 22); id = 1.11 price= 22
pencil.showdata();
}
Class Templates
template <class a, class b>
class item
{ private:
a id;
b price;
public: Output
indata(a one, b two) { id= one; price=two; }
showdata(){cout<<"\n id = " <<id; cout<< "
price= " << price; }
}; id = 4 price= 44
Analysis of Templates
- Comparison with function Overloading
- Comparison with Polymorphism
Advantages:
It provides a data type free coding technique.
Useful in generic programming.
Good for code reuse.
Useful to build powerful libraries.
Greater modifiability
Templates
Disadvantages :