sum using templates

Templates are useful, when we do not need to write function based in types. Take for instance, you need to sum two integers and return an integer. And in the second case, you need to sum two floats and return float value.

So, you will have to write two functions. So, instead use templates.

#include<iostream>
using namespace std;
template <class T>
T sum(T a ,T b){
	T sum;
	sum = a+b;
	return sum;
}
int main(){
	int a = 10;
	int b = 20.0;
	cout<<"The sum of two int values are : "<<sum(a,b)<<endl;
	float c = 12.5;
	float d = 32.7;
	cout<<"The sum of two float values are : "<<sum(c,d)<<endl; 
	return 0;
}
output of the above program. sum using templates
output of the above program. sum using templates

One Reply to “sum using templates”

Leave a Reply

Your email address will not be published. Required fields are marked *