Template-in-C++ .

In this session i have discussed template in C++ .


Template is a new and powerful feature in C++ . It is used to work with generics . It allow you to work with different data types in function or class .

The concept of template can be used with two different ways .

1-Function Template

2-Class Template


1-Function Template

The normal function can work with one set of data types . But the function template can work with different data types .

It is better to use the function template because , It is work with different data types without any modification of function code .

Function Template declaration .

    template <class T>
    T function-name(T parameter)
    

In the above code T is the template parameter data type which can accept any data type like int , float etc .

Example : Write a program that demonstrate the use of function template .

    #include<iostream>
    using namespace std; 
    template <class T>
    T sum(T x,T y)
    {
        return(x+y);
    }
    int main()
    {
       int x,y;
       float a,b;
       cout<<"\nEnter the two integer value :\n";
       cin>>x;
       cin>>y;
       cout<<"\nsum : "<<sum(x,y);
       cout<<"\nEnter the two float value\n";
       cin>>a;
       cin>>b;
       cout<<"\nsum : "<<sum(a,b);
       return 0;
    }
    OUTPUT : Enter the two integer value
             20
             10
             sum : 30   
             Enter the two integer value
             20.4
             40.6
             sum : 61
    

Class Template

Like function template you can also create the class template for generic operation . The class template is useful when need to define the independent data type .

Class Template declaration

    template <class T>
    class class-name
    {
            T variable;
            public :
            T function-name(T parameter)
            {
                function body
            }
    };
    

Create the class template object

To create the class template object you need to specify the data type inside the <> .

    class-name<data-type>object-name;
    

Example : Write a program that demonstrate the use of class template .

    #include<iostream>
    using namespace std; 
    template <class T>
    class A
    {
        T x,y;
        public :
        T add(T a, T b)
        {
            return(a+b);
        }
    };
    int main()
    {
       A<int> obj;
       cout<<"\nsum : "<<obj.add(20,10);
       A<float> obj1;
       cout<<"\nsum :"<<obj1.add(30.4,10.3);

       return 0;
    }
    OUTPUT : sum : 30
             sum  : 40.7
    

In the above code i have used the cerr for displaying the error . It is used to display the error message on screen .

Welcome to AndroidATPoint.

back image                     next image