Return to Chapter 8

C++ template

function template

e.g.
void Print(int *A, const int n)
{
  for (int i=0; i<n; i++)
      cout << A[i] << " ";
  cout << endl;
}

void main()
{
  int a[5] = {1,2,3,4,5};
  float b[3] = {1.2,3.4,5.6};

  Print(a,5);
  Print(b,3);   //illegal ....
}

Solution?
1. Create Print_int, Print_float,.... for each type.
2. use function template.

e.g.
template<class T>   // It is not end by ';', T can be change to any name
void Print(T *A, const int n)
{
  for (int i=0; i<n; i++)
      cout << A[i] << " ";
  cout << endl;
}

void main()
{
  int a[5] = {1,2,3,4,5};
  float b[3] = {1.2,3.4,5.6};
  char c[6] = "Hello";

  Print(a,5);
  Print(b,3);   //OK
  Print(c,6);   //OK
}

class template

similar to function template.  No specific type given for array element type.  The actual type is given during the declaration of objects.
Declaration 1.
 
class CL
{
....
....
int A[10];
}


Declaration 2.
 

template<class T>    //It is not end by ";".  T can be changed to any name
class CL
{
....
....
T A[10];
}


CL<int> OBJ1;  // A in OBJ1 is an array of 10 int.
CL<char> OBJ2; // A in OBJ2 is an array of 10 char.