Using Templates in C++
-Sanchit Karve
born2c0de@hotmail.com
INTRODUCTION
Before I start this tutorial I assume that you have a working knowledge of Object Oriented Program (OOP) in C++. Without this, the tutorial will be of no use to you.
This tutorial shows you how to reuse code, save typing time, prevent time spent on
debugging and saving source-code space.
OK. Let me take a common example. The great min() function returns the value which is lowest from the given two arguments.I shall show two examples now. One without Templates and one with Templates. Here is the first program:
int min(int a,int b)
{
return (a < b)?a:b ;
}
float min(float a,float b)
{
return (a < b)?a:b ;
}
char min(char a,char b)
{
return (a < b)?a:b ;
}
void main()
{
int a=10,b=5;
cout<<min(a,b)<<'\n';
char p='A',q='Z';
cout<<min(p,q)<<'\n';
float z=1.91,x=3.98;
cout<<min(z,x)<<'\n';
}
5
A
1.91
Function Overloading doesn't help much as far as typing time and source space is
concerned. Also if you find an error in one such function, you have to correct it
in all the other functions as well. With Templates all the work becomes a lot
easier. Let's see the Templated version now:
T min(T a,T b)
{
return (a < b)?a:b ;
}
void main()
{
int a=10,b=5;
cout<<min(a,b)<<'\n';
char p='A',q='Z';
cout<<min(p,q)<<'\n';
float z=1.91,x=3.98;
cout<<min(z,x)<<'\n';
}
Same output. Nearly the same executable size. But what we have achieved is that the time we take to type the code is reduced. The code looks more readable and incase there is an error just correcting it here will make the change for all data types accessing this function.
Let me explain what happens at compile time.When the function is first called
with this:
It goes to the function min(). Now T is the value that will be substituted with
the data type of the parameter.So here T will be int. So dynamically the function
declaration becomes like this:
In the second case T takes the form of a char and so on...The compiler on every call still has to generate seperate functions for each data type but what we are saving are typing time and debugging ease.
Some of you might wonder "what if we want all data-types to access a templated function except one?" Like for example in a abs() function we would like all data types to access it except a char data-type.What do we do then? Well in such a case we override the function call like this:
int abs(T no)
{
return (no<0)?(no*-1):no;
}
void abs(char a){}
This way even if accidentaly a char data type is used as a parameter to the abs functio, the overloaded function gets called. Not the Templated version.
What if we wanted a multi-parametered Templated Function? Here is the syntax:
void function(T item,Q data){}
You now know enough of Function Templates. Now it's time to move onto Class Templates.
