|
Templates |
Generic functions and classes .
Generic function applies the same set of instructions on data of different type . The type of the data is passed to the as a parameter . Please see C++ Examples.
Similar to template functions , template classes can can also be defined in which certain data types can be determined by the class instances .
#include<iostream.h>
const int SIZE = 10;
template < class D>
class List {
private :D data[SIZE];
int count;
public:
List(){count=0;}
void add ( D ch);
D remove ();
};
//------------------------------
template < class D >
void List <D> :: add ( D ob)
{
if (count == SIZE)
cout<<"List is full";
else
{
data[count] = ob ;
count++;
}
}
//------------------------------
template < class D >
D List <D> ::remove()
{
if (count == 0 ){
cout<<"List is empty";
return (D(0));
}
else{
count--;
return (data[count]);
}
}
//------------------------------
int main(){
List<char> charL; // List of characters
charL.add('A');
charL.add('B');
charL.add('C');
for(int i=0; i<3; i++)
cout << "remove :"<<charL.remove()<<endl;
List<double> doubleL; // List of double numbers
doubleL.add(1.1);
doubleL.add(9.9);
doubleL.add(100.55);
for(i=0; i<3; i++)
cout << "remove :"<<doubleL.remove()<<endl;
}