Templates

996 views

Published on

programming fundamentals ( all about templates )

Published in: Education, Technology, Business
  • Be the first to comment

Templates

  1. 1. Definition:  Templates are used to define generic definition of functions or classes.  A template is not related to specific data types and can work with different data types.  Can re-use same code with int, string, etc.
  2. 2. There are two types of templates: Function templates Class templates
  3. 3.  Function templates are special functions that can operate with generic types.  This allows us to create a function template whose functionality can be adapted to more than one type or class without repeating the entire code for each type.  Same code is re-used for different types
  4. 4. Syntax: template <class T> T FunctionName (Parameter (s));
  5. 5. Example: #include<iostream.h> #include<conio.h> using namespace std; template<class T> void swap(T&x,T &y) { t temp=x; x=y; y=temp; } void fun(int a,int b,float c,float d) { cout<<"na and b before swaping :"<<a<<"t"<<b; swap(a,b); cout<<"na and b after swaping :"<<a<<"t"<<b; cout<<"nnc and d before swaping :"<<c<<"t"<<d; swap(c,d); cout<<"nc and d after swaping :"<<c<<"t"<<d; } void main() { int a,b; float c,d; clrscr(); cout<<"Enter A,B values(integer):"; cin>>a>>b; cout<<"Enter C,D values(float):"; cin>>c>>d; fun(a,b,c,d); getch(); }
  6. 6. Output: Enter A, B values (integer): 10 20 Enter C, D values (float): 2.50 10.80 A and B before swapping: 10 20 A and B after swapping: 20 10 C and D before swapping: 2.50 10.80 C and D after swapping: 10.80 2.50
  7. 7. Program: #include<iostream> #include<conio.h> using namespace std; template <class Type> Type Max(Type a, Type b) { if(a>b) return a; else return b; } Void main() { int n; float m; n=Max(10, 50); cout<<“Maximum of two integers:“<<n<<endl; m=Max(4.8, 2.2); Cout<<“Maximum of two float: “<<m<<endl; getch(); } Output: Maximum of two integers: 50 Maximum of two floats:4.8
  8. 8. Class templates are generally used for data storage classes. Stacks and linked lists are examples of data storage classes. The examples of these classes(data storage classes) that we present could store data of only a single basic type.
  9. 9. The example shown, could store data only of type “int” that is:
  10. 10.  class Stack  { › private:  int st[MAX]; //array of int  int top; //index number of top of stack › public:  Stack(); //constructor  void push(int var); //takes int as argument  int pop(); //returns int value  };
  11. 11. If we wanted to store data of type long in a stack, we would need to define a completely new class.
  12. 12.  class LongStack  { › private:  long st[MAX]; //array of longs  long top; //index number of top of stack › public:  LongStack(); //constructor  void push(long var); //takes long as argument  long pop(); //returns long value  };
  13. 13. Templates make it possible to use one function or class to handle different data types.
  14. 14.  The basic syntax for declaring template class:  template <class Type>  class Cont  { › ……  };
  15. 15. Example of class template that handle variables of all / different data types is shown
  16. 16.  // tempstak.cpp  // implements stack class as a template  #include <iostream.h>  using namespace std;  const int MAX = 100; //size of array  template <class Type>  class Stack  {  private:  Type st[MAX]; //stack: array of any type  int top; //number of top of stack  public:  Stack() //constructor  { top = -1; }  void push(Type var) //put number on stack  { st[++top] = var; }  Type pop() //take number off stack  { return st[top--]; }
  17. 17.  int main()  {  Stack<float> s1; //s1 is object of class Stack<float>  s1.push(1111.1F); //push 3 floats, pop 3 floats  s1.push(2222.2F);  s1.push(3333.3F);  cout << “1: “ << s1.pop() << endl;  cout << “2: “ << s1.pop() << endl;  cout << “3: “ << s1.pop() << endl;  Stack<long> s2; //s2 is object of class Stack<long>  s2.push(123123123L); //push 3 longs, pop 3 longs  s2.push(234234234L);  s2.push(345345345L);  cout << “1: “ << s2.pop() << endl;  cout << “2: “ << s2.pop() << endl;  cout << “3: “ << s2.pop() << endl;  return 0;  }
  18. 18. 1: 3333.3 //float stack 2: 2222.2 3: 1111.1 1: 345345345 //long stack 2: 234234234 3: 123123123
  19. 19.  Class templates differ from function templates in the way they are instantiated.  To create an actual function from a function template, you call it using arguments of a specific type.
  20. 20.  Old C language signaled many errors for returning a particular value from the functions.  Setjump() and Longjump() functions were used for handling errors there (very difficult to use).  This approach is not appropriate in C++.  It handles errors in a different way using “Exceptions”.
  21. 21. The exception syntax consists of:  First of all, there should be an exception class.  Throw Exception (To handle an error)  Try Block (A code that uses objects)  Catch Block (Catches exception through member function)
  22. 22.  // not a working program  class AClass //a class  {  public:  class AnError //exception class  {  };  void Func() //a member function  {  if( /* error condition */ )  throw AnError(); //throw exception  }  };  int main() //application  {  try //try block  {  AClass obj1; //interact with AClass objects  obj1.Func(); //may cause error  }  catch(AClass::AnError) //exception handler  { //(catch block)  //tell user about error, etc.  }  return 0;  }
  23. 23. // demonstrates exceptions  #include <iostream>  using namespace std;  const int MAX = 3; //stack holds 3 integers  class Stack  {  private:  int st[MAX]; //array of integers  int top; //index of top of stack  public:  class Range //exception class for Stack  { //note: empty class body  };
  24. 24.  Stack() //constructor  { top = -1; }  void push(int var)  {  if(top >= MAX-1) //if stack full,  throw Range(); //throw exception  st[++top] = var; //put number on stack  }  int pop()  {  if(top < 0) //if stack empty,  throw Range(); //throw exception  return st[top--]; //take number off stack  }  };
  25. 25.  int main()  {  Stack s1;  try  {  s1.push(11);  s1.push(22);  s1.push(33);  // s1.push(44); //oops: stack full  cout << “1: “ << s1.pop() << endl;  cout << “2: “ << s1.pop() << endl;  cout << “3: “ << s1.pop() << endl;  cout << “4: “ << s1.pop() << endl; //oops: stack empty  catch(Stack::Range) //exception handler  {  cout << “Exception: Stack Full or Empty” << endl;  }  cout << “Arrive here after catch (or normal exit)” << endl;  return 0;  }
  26. 26.  First of all, exception class should be specified as follows: Class Range { empty class body};
  27. 27.  Exception will occur in previous program if application tries to pop a value when stack is empty and push a value when stack is full.  Throw Range() will perform this task here.
  28. 28.  Statements that manipulate stack (class name) objects, are enclosed in try block. try { //code that operates on objects that might cause exception }
  29. 29.  Code that handles exceptions is enclosed in braces, preceded by catch keyword. catch(stack::Range) { //code that handles exception }
  30. 30.  Normal execution outside try block.  Control enters the try block.  An error occurs in try block (in main function).  Member function throws an exception.  Control transfers to exception handler.
  31. 31. // demonstrates two exception handlers  #include <iostream>  using namespace std;  const int MAX = 3; //stack holds 3 integers  class Stack  {  private:  int st[MAX]; //stack: array of integers  int top; //index of top of stack  public:  class Full { }; //exception class  class Empty { }; //exception class  Stack() //constructor  { top = -1; }  void push(int var) //put number on stack  {  if(top >= MAX-1) //if stack full,  throw Full(); //throw Full exception  st[++top] = var;  }
  32. 32.  int pop() //take number off stack  {  if(top < 0) //if stack empty,  throw Empty(); //throw Empty exception  return st[top--];  }  };  int main()  {  Stack s1;  try  {  s1.push(11);  s1.push(22);
  33. 33.  s1.push(33);  // s1.push(44); //oops: stack full  cout << “1: “ << s1.pop() << endl;  cout << “2: “ << s1.pop() << endl;  cout << “3: “ << s1.pop() << endl;  cout << “4: “ << s1.pop() << endl; //oops: stack empty  }  catch(Stack::Full)  {  cout << “Exception: Stack Full” << endl;  }  catch(Stack::Empty)  {  cout << “Exception: Stack Empty” << endl;  }  return 0;  }
  34. 34.  // exceptions with arguments  #include <iostream>  #include <string>  using namespace std;  class Distance //English Distance class  {  private:  int feet;  float inches;  public  class InchesEx //exception class  {
  35. 35.  public:  string origin; //for name of routine  float iValue; //for faulty inches value  InchesEx(string or, float in) //2-arg constructor  {  origin = or; //store string  iValue = in; //store inches  }  }; //end of exception class  Distance() //constructor (no args)  { feet = 0; inches = 0.0; }
  36. 36.  Distance(int ft, float in) //constructor (two args)  {  if(in >= 12.0)  throw InchesEx(“2-arg constructor”, in);  feet = ft;  inches = in;  }  void getdist() //get length from user  {  cout << “nEnter feet: “; cin >> feet;  cout << “Enter inches: “; cin >> inches;
  37. 37.  if(inches >= 12.0)  throw InchesEx(“getdist() function”, inches);  }  void showdist() //display distance  { cout << feet << “‟-” << inches << „”‟; }  };  int main()  {  Distance dist1(17, 3.5); //2-arg constructor  Distance dist2; //no-arg constructor  dist2.getdist(); //get value  //display distances
  38. 38.  cout << “ndist1 = “; dist1.showdist();  cout << “ndist2 = “; dist2.showdist();  }  catch(Distance::InchesEx ix) //exception handler  {  cout << “nInitialization error in “ << ix.origin  << “.n Inches value of “ << ix.iValue  << “ is too large.”;  }  cout << endl;  return 0;  }
  39. 39.  The exception statements need not be in the try block directly.  It can be in a function that is called by a statement in try block.  However, try part must be included before catch part.
  40. 40.  The class libraries sold by any developer may contain errors. They can cause problems. These problems can be resolved using Exceptions.
  41. 41.  Do not use exceptions for simple purposes that can be solved using loops and other structures. Use exceptions for handling difficult tasks only because they effect the program size.
  42. 42.  In exception mechanism, destructors are called automatically. So the space reserved by them is swiped clean easily.  Code in every exception will be reset.
  43. 43.  When you catch an exception, sometimes you terminate your application. Exception mechanism cleans up chores before terminating. In short, it executes destructors. If there is no exception handler, the program is terminated by operating system.

×