Wednesday, June 27, 2012

Templates

A generic function defines a general set of operations that will be applied to various types of data. For example using template to swap a float, int or char.

Function Template:

// Function template example. p.751 BorlandC
#include <iostream>
using namespace std;
// This is a function template.
//void swapargs(int &a, int &b)
//{
////X temp;
//int temp = a;
//a = b;
//b = temp;
//}
//void swapargs(float &a, float &b)
//{
////X temp;
//int temp = a;
//a = b;
//b = temp;
//}
//void swapargs(char &a, char &b)
//{
////X temp;
//int temp = a;
//a = b;
//b = temp;
//}
template <class X> 
void swapargs(X &a, X &b)
{
X temp;
temp = a;
a = b;
b = temp;
}

int main()
{
int i=10, j=20;
float x=10.1, y=23.3;
char a='x', b='z';
cout << "Original i, j: " << i << ' ' << j << endl;
cout << "Original x, y: " << x << ' ' << y << endl;
cout << "Original a, b: " << a << ' ' << b << endl;
swapargs(i, j); // swap integers
swapargs(x, y); // swap floats
swapargs(a, b); // swap chars
cout << "Swapped i, j: " << i << ' ' << j << endl;
cout << "Swapped x, y: " << x << ' ' << y << endl;
cout << "Swapped a, b: " << a << ' ' << b << endl;
return 0;
}

Output:
Original i, j: 10 20
Original x, y: 10.1 23.3
Original a, b: x z
Swapped i, j: 20 10
Swapped x, y: 23.3 10.1
Swapped a, b: z x

Class Template:

// class templates
#include <iostream>
using namespace std;

template <class T>
class mypair {
    T a, b;
  public:
    mypair (T first, T second)
      {a=first; b=second;}
    T getmax ();
};

template <class T>
T mypair<T>::getmax ()
{
  T retval;
  retval = a>b? a : b;
  return retval;
}

int main () {
  mypair <int> myobject (100, 75);
  cout << myobject.getmax();
  return 0;
}

No comments: