Template in C++



Templates are the base of generic programming, which involves writing code in a way that is independent of any particular type.
A template is  formula for creating a generic class or a function.
It is basically used to perform the generic data type programming. Using a template, it is possible to create generic functions and classes. A generic function defines a general set of operations that will apply to various types of data.
By using a generic function, a single general procedure can be applied to a wide range of data.

There are two types of template
1.       Function Template
2.       Class Template

Example of Function Template
C++ program using function template to find out the sum of two variable.
#include<iostream.h>
#include<conio.h>
template<class r>
void main ()
{
                clrscr ();
                int a, b;
                float c, d;
                cout<”Enter a and b”;
                cin>>a>>b;
                sum(c, d);
                getch();
}
void sum (r a, r b)
{
                r c;
                c = a + b;
                cout<<c;
}
Input:
Enter a and b 3 4
Output:
7


Example of Function Template
C++ program using function template to find out the sum of :
1.       Integer elements of the array
2.       Float elements of the array

#include<iostream.h>
#include<conio.h>
template<class r>
void main ()
{
                clrscr ();
                int a[5], i;
                float b[5];
                cout<<”Enter integer value of array = ”;
                for (i=0;  i<=4; i++)
                {
                                cin>>a[i];
                }
                sum(a, 5);
                cout<<”Enter float value of array = ”;
                for (i=0;  i<=4; i++)
                {
                                cin>>a[i];
                }
                sum(b, 10);
                getch ();
}
void sum (r a[ ], int n )
{
                s=0;
                int i;
                for (i=0;  i<=n; i++)
                {
                                s = s + a[i];
                }
                cout<<s;
}

Example of Class Template

C++ program using Class template to find out the sum of two variable.
#include<iostream.h>
#include<conio.h>
template<class t>
class sum
                {
                                t a, b, c;
                                public:
                                void get ();
                };
template <class t>
void sum <t> :: get ()
{
                cin>>a>>b;
                c = a + b;
                cout<<c;
}
void main ()
{
                clrscr ();
                sum <int> st;
                sum <float> mt;
                st.get ();
                mt.get ();
                getch ();
}

Input:
3 4
Output:
7

No comments:

Post a Comment