Monday, 2 March 2009

Example of C++ Templates

Program to show how templates work in a very simple way:




//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Note this program shows Template example

#include<iostream>

using namespace
std;

template
<class T> class Arith
{

public
:
T Add(T a, T b)
{

return
a + b;
}
};


template
<class T, class U> class ArithNew
{

public
:
T Add(T a, U b)
{

return
(T)(a + b); //the return type is casted otherwise a warning will be generated
}
};


int
main(void)
{

Arith<int> ar1;
int
x = ar1.Add(3, 5);
cout<<"x = "<<x<<endl;

Arith<double> ar2;
double
y = ar2.Add(3.3, 1.2);
cout<<"y = "<<y<<endl;

//Arith<int> ar3;
//double z = ar3.Add(3, 1.2);
//cout<<"z = "<<z<<endl;
//The above is possible but loss of data and no flexibility. Cant mix two types

ArithNew<double, int> ar4;
double
xx = ar4.Add(5.5, 2);
cout<<"xx = "<<xx<<endl;

//reversing the same as above
ArithNew<int, double> ar5;
int
yy = ar5.Add(2, 5.5); //works without warning because of return type being casted otherwise warning
cout<<"yy = "<<yy<<endl;

return
0;
}






No comments:

Post a Comment