Page 1 of 1

Function And Class Templates Tutorial Reuse code with Templates in C++ Rate Topic: ****- 2 Votes

#1 born2c0de  Icon User is offline

  • printf("I'm a %XR",195936478);
  • member icon

Reputation: 180
  • View blog
  • Posts: 4,667
  • Joined: 26-November 04

Posted 21 December 2004 - 02:49 AM

This tutorial shows you how to reduce typing, reuse code and speed up development using Templates.

Feel free to contact me for queries regarding the subject.

Thanks,
Sanchit

TEMPLATES IN C++
-Sanchit Karve
-born2c0de@hotmail.com






INTRODUCTION



Before I start this tutorial I assume that you have a Working Knowledge of 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 gr8 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.



#include <iostream>

using namespace std;

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;
}


int main()
{
 int a=10,b=5;
 cout<<min(a,b )<<'\n';
 char p='A',q='Z';
 cout<<min(p,q)<<'\n';
 float z=1.91f,x=3.98f;
 cout<<min(z,x)<<'\n';
 return 0;
}



OUTPUT:

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...

#include <iostream>

using namespace std;

template <class T>
T min(T a,T b )
{
  return (a < b )?a:b;
}

int 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';
 return 0;
}



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 us first called
with this:
cout<<min(a,b ); //a and b are int's

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...
int min(int a,int b )

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...

template <class T>
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
function..the overloaded function gets called...not the Templated version.

What if we wanted a multi-parametered Templated Function? Here is the Syntax

template <class T,class Q>
void function(T item,Q data){}


You now know enough of Function Templates.Now it's time to move onto Class
Templates.



OK.Now let us assume that we have a Stack class(Data Structure) that is capable
of storing only int's. Now suppose you want it to store float's as well.You
would normally write the whole class again by Copy/Pasting the Previous class
and make the necessary Changes.But hey,There is a much better alternative.Using
templates, you can manage just one class that handles different data-types.That
way even if you find an error in your class,fixing it will make changes to all
the data-types. Here is an example of a templated stack data structure.


#include <dos.h>		   // For sleep()
#include <iostream>	 // For I/0
#include <windows.h>	 // FOR MessageBox() API
#include <conio.h>

using namespace std;

#define MAX 10		// MAXIMUM STACK CONTENT

template <class T>	// Using Templates so that any type of data can be
		   // stored in Stack without multiple defination of class
class stack
{

  protected:

  T arr[MAX];	   // Contains all the Data

  public:
	T item,r;
	int top;		//Contains location of Topmost Data pushed onto Stack
 stack()		 //Constructor
  {
  for(int i=0;i<MAX;i++)
{
  arr[i]=NULL;			 //Initialises all Stack Contents to NULL
}

  top=-1;	  //Sets the Top Location to -1 indicating an empty stack
  }

void push(T a)  // Push ie. Add Value Function
 {
top++;		// increment to by 1
if(top<MAX)
 {
arr[top]=a;		  //If Stack is Vacant store Value in Array
 }
 else	// Bug the User
 {
MessageBox(0,"STACK IS FULL","STACK WARNING!",MB_IConstop);
top--;
 }
 }

T pop()				  // Delete Item. Returns the deleted item
 {
if(top==-1)
{
MessageBox(0,"STACK IS EMPTY\n","WARNING",MB_IConstop);
return NULL;
}
else
{
T data=arr[top];	 //Set Topmost Value in data
arr[top]=NULL;	   //Set Original Location to NULL
top--;			   // Decrement top by 1
return data;		 // Return deleted item
}
 }
};


int main()
{
 stack <int>a;	// Create object of class a with int Template
 int opt=1;
 while (opt!=3)
 {
 //clrscr();
 cout<<" MAX STACK CAPACITY="<<((MAX-a.top)-1)<<"\n\n\n\n";
 cout<<"1) Push Item\n";
 cout<<"2) Pop Item\n";
 cout<<"3) Exit\n\n";
 cout<<"Option?";
 cin>>opt;
 switch(opt)
 {
  case 1:
  cout<<"Which Number should be pushed?";
  cin>>a.item;
  a.push(a.item);
  break;

  case 2:
  a.r=a.pop();
  cout<<"Item popped from Stack is:"<<a.r<<endl;
  //sleep(2);
  break;
 }
 }
 return 0;
 }
 



Everything looks similiar except an object declaration
stack <int> s1;
means that the value T is substituted by int. User-Defined Data Types
can also be used provided the required overloaded operator functions are
present.

In case if we define the class functions outside the templated class,the
syntax changes a bit.For a Constructor:
template <class T>
		stack <T>::stack()
		{
		//Code
		}


Yes,we have to define that template thing everytime we write a function
outside the class.But if a function returns an object of the same
templated class the syntax would be like this:
stack <T> stack <T>::func(int data)
		{
		//code
		}



Templates can also have pre-defined values like this:
template <class T,const int max=10>
		class stack
		{
		  private:
		  T data[max];
		  //rest of the members...
		};



Templates can be inherited as well like this:
class newstack:public stack<T>
		{
		 //members...
		};



That's all about templates.If you use Templates Frequently you will save
a lot of typing and debugging time.

Suggestions/Queries can be brought to my notice by posting here.


-Sanchit Karve
born2c0de@hotmail.com

Download the Text File:
Attached File  tpltut.txt (7.52K)
Number of downloads: 1239

*** MOD EDIT: Added code tags ***

This post has been edited by JackOfAllTrades: 22 October 2009 - 01:53 PM


Is This A Good Question/Topic? 2
  • +

Replies To: Function And Class Templates Tutorial

#2 shikha  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 30
  • Joined: 23-May 06

Posted 24 May 2006 - 01:02 AM

got quite a clear pic abt templates........
one more query..... wat is the diff between the member functions declared under private n protected ....
Was This Post Helpful? 0
  • +
  • -

#3 born2c0de  Icon User is offline

  • printf("I'm a %XR",195936478);
  • member icon

Reputation: 180
  • View blog
  • Posts: 4,667
  • Joined: 26-November 04

Posted 24 May 2006 - 09:24 AM

It's all got to do with inheritance.

Member functions under the private section are not accessible even in class that are inherited from the base class.

However Member functions from the protected section are accessible in classes that are derived from the base class.

But outside of a class(which is not inherited from the base class), both private and protected do the same job.
Was This Post Helpful? 0
  • +
  • -

#4 Zerobu  Icon User is offline

  • Black Hatter

Reputation: 13
  • View blog
  • Posts: 1,822
  • Joined: 14-January 08

Posted 19 September 2009 - 01:10 PM

something needs to be done with these emoticons, the' re annoying.
Was This Post Helpful? 0
  • +
  • -

#5 Guest_Rajendra*


Reputation:

Posted 20 February 2010 - 10:24 PM

Hi, Nice tutorial!
I have a question!
Suppose I have written a function template
template <typename T>
void swap(const T& _x, const T& _y)
{
T temp;
temp = _x;
_x = _y;
_y = _x;
}



And now I am calling this template function like following:

int a = 3, b = 5;
swap(a, B)/>;
float fa = 3.3, fb = 5.5;
swap(fa, fb);
char ca = 'R', cb = 'K';
swap(ca, cb);



1. I was curious to know what happens at compile time?
I know that template function is source code reuse not object code reuse.
2. How does compiler calls appropriate function for int, float, or char?
3. If I am calling this function in a for loop, how does compiler go to appropriate function to start execution from that address?
4. Does compiler maintains some kind of function address table as it maintains a vtable for virtual functions?
5. What is the difference between typename T and class T?

Thanks !
Was This Post Helpful? 0

#6 Guest_Rajendra*


Reputation:

Posted 20 February 2010 - 10:28 PM

Sorry some typos!
line _y = _x; in definition of swap function should read as _y = temp;
Was This Post Helpful? 0

#7 PlasticineGuy  Icon User is offline

  • mov dword[esp+eax],0
  • member icon

Reputation: 281
  • View blog
  • Posts: 1,436
  • Joined: 03-January 10

Posted 23 February 2010 - 03:28 AM

One little nitpick:

Quote

So Dynamically the Function
Declaration becomes like this...
The templates for functions are actually sorted out statically at compile time.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1