Sunday, 3 April 2011

5. Templates

Templates are a feature of the C++ programming language that allow functions and classes to operate with generic types . This allows a function or class to work on many different data types without being rewritten for each one.
Templates are of great utility to programmers in C++, especially when combined with multiple inheritance and operator overloading.

Function templates

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.

In C++ this can be achieved using template parameters. A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function. These function templates can use these parameters as if they were any other regular type.

types of the templates:
1. function templates
2. generic classes or classes
3. explicit template specialization
2 Advantages and disadvantages
3 Generic programming features in other languages

The format for declaring function templates with type parameters is:


// function template
#include <iostream>
#include<conio.h>

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

void main ()
{
  int i=5, j=6, k;
  long l=10, m=5, n;
  k=Max<int>(i,j);
  n=Max<long>(l,m);
  cout << k << endl;
  cout << n << endl;
  

}

Class templates

We also have the possibility to write class templates, so that a class can have members that use template parameters as types. For example:

#include<iostream.h>
#include<conio.h>
template <class T>
class Demo
{
 T x,y,z;
 friend void display();
 public:
 //member function declarations
  temple();
void display();
}; //end of temple class
//defining member functions outside of its class
template <class T>
Demo::Demo()
  {
   x=2;
   y=3;
   z=4;
  }
template <class T>
 void Demo::display()
 {
  cout<<x<<endl<<y<<endl<<z<<endl;
 }

 void main()
 {
     Demo<int>obj;  //creating object, T is replaced with int
     clrscr();
      obj.display();
      getch();
}



Other Examples on Class Templates:
Single Linked List program

No comments:

Post a Comment