# Templates

Published on January 2017 | Categories: Documents | Downloads: 51 | Comments: 0 | Views: 429
of 6

## Content

TEMPLATES IN C++ -Sanchit Karve [email protected]

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 #include #include #include <dos.h> <iostream> <windows.h> <conio.h> // For sleep() // For I/0 // FOR MessageBox() API

using namespace std; #define MAX 10 template <class T> nation of class class stack { protected: T arr[MAX]; public: T item,r; int top; stack() { // Contains all the Data // MAXIMUM STACK CONTENT // Using Templates so that any type of data can be // stored in Stack without multiple defi

//Contains location of Topmost Data pushed onto Stack //Constructor for(int i=0;i<MAX;i++) { arr[i]=NULL;

//Initialises all Stack Conte

nts to NULL }

top=-1; stack }

//Sets the Top Location to -1 indicating an empty

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 { P); top--; } } T pop() { // Delete Item. Returns the deleted item if(top==-1) { MessageBox(0,"STACK return NULL; } else { T data=arr[top]; arr[top]=NULL; top--; return data; } } }; 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; // Bug the User MessageBox(0,"STACK IS FULL","STACK WARNING!",MB_ICONSTO

IS EMPTY\n","WARNING",MB_ICONSTOP);

//Set Topmost Value in data //Set Original Location to NULL // Decrement top by 1 // Return deleted item

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\Querys can be brought to my notice at [email protected]

HAVE FUN CODING!!!

-Sanchit Karve [email protected]

## Recommended

#### templates

Or use your account on DocShare.tips

Hide

Forgot your password?

Or register your new account on DocShare.tips

Hide

Lost your password? Please enter your email address. You will receive a link to create a new password.

Back to log-in

Close