Chapter 8: Templates: Bibha Sthapit Asst. Professor Ioe, Pulchowk Campus
Chapter 8: Templates: Bibha Sthapit Asst. Professor Ioe, Pulchowk Campus
BIBHA STHAPIT
ASST. PROFESSOR
IOE, PULCHOWK CAMPUS
Introduction
• Template supports generic programming, which allows
developing reusable software components such as functions,
classes supporting different data types in a single frame work.
– For example , class vector can be used for int, float or double vector
type. Function ‘ addition’ can be used for addition of any type of data
• When object or variable of specific type is defined for actual
use, the template definition for class or function is substituted
with required data type.
• Types of templates :
– Function template
– Class template
Function template
• A function template specifies how an individual function
can be constructed.
• Syntax :
template <class / typename typeT >
ret-type func_ name ( param List of typeT )
{
/ / function body
}
• Where, typeT is a placeholder
template <class T> int a,b;
void swaping (T & x, T & y) cout<<"Enter two integers:"<<endl;
{ T z; cin>>a>>b;
z=x; swaping(a,b);
x=y; cout<<a<<ends<<b<<endl;
y=z; Output:
} float p,q; Enter two characters:
cout<<"Enter two real rt
main( ) numbers:"<<endl; tr
{ cin>>p>>q; Enter two integers:
char ch1,ch2; swaping(p,q); 79
cout<<"Enter two characters:"<<endl; cout<<p<<ends<<q<<endl; 97
cin>>ch1>>ch2; } Enter two real numbers:
swaping(ch1,ch2); 5.6 8.2
cout<<ch1<<ends<<ch2<<endl; 8.2 5.6
Function template with multiple parameters
}
Default argument with class template
template <class T=float, int n=5>
class Array main()
{ T a[n]; template <class T, int n>
{
public: void Array<T, n>::display() cout<<"For float type"<<endl;
void setdata() { Array < > ob1;
T sum=0; ob1.setdata( );
{ for (int i=0; i<n; i++)
for (int i=0; i<n; i++) ob1.display();
cin>>a[i];
sum+=a[i];
}
cout<<"For int type"<<endl;
void display(); cout<<"Sum="<<sum<<endl;
Array <int,3> ob2;
}; }
ob2.setdata();
ob2.display();
}
Derived class template
• Three cases of derived class templates:
– 1. Deriving template from a template
– 2. Deriving non-template from template
– 3. Deriving template from non template
1. Deriving template from a template