+92 332 4229 857 99ProjectIdeas@Gmail.com

Template (C++)


Template

Function overloading is used to declare a function with same number of parameters but are of different types, but it introduces code redundancy because we have to copy the same function many times as we want to override that function with same number of parameters but with different types, so to overcome this inefficiency templates are used which provide us the facility to make a general type of function which accept different data-types of parameter depending on the paramenters specified in the function call.


Code


#include "stdafx.h"

#include "iostream"

#include "conio.h"


using namespace std;


template<class T>

T add(T x,T y)

{

            return x+y;

}


template<class T>

T add(T x,T y,T z)

{

            return x+y+z;

}


int main()

{

            cout<<"5 + 5                = "<<add(5,5)<<endl;

            cout<<"5.6 + 5.7            = "<<add(5.6,5.7)<<endl;

            cout<<"'A'+ '0'             = "<<add('A','0')<<endl;

            cout<<"int('A') + int('0')  = "<<add(int('A'),int('0'))<<endl;

            cout<<"char(47) + char(50)  = "<<add(char(47),char(50))<<endl;


            cout<<"5 + 5 + 5                          = "<<add(5,5,5)<<endl;

            cout<<"5.6 + 5.7 + 5.8                    = "<<add(5.6,5.7,5.8)<<endl;

            cout<<"'A'+ '0' + '1'                     = "<<add('A','0','1')<<endl;

            cout<<"int('A') + int('0') + int('1')     = "<<add(int('A'),int('0'),int('1'))<<endl;

            cout<<"char(47) + char(50) + char(1)      = "<<add(char(47),char(50),char(1))<<endl;


            _getche();

            return 0;

}


Output

5 + 5                = 10

5.6 + 5.7            = 11.3

'A'+ '0'             = q

int('A') + int('0')  = 113

char(47) + char(50)  = a

5 + 5 + 5                          = 15

5.6 + 5.7 + 5.8                    = 17.1

'A'+ '0' + '1'                     = ó

int('A') + int('0') + int('1')     = 162

char(47) + char(50) + char(1)      = b


0 comments: