Friday, June 27, 2008

C++ templates: an introduction

Have you ever needed to have multiple versions of the same function, with the only difference being the date type used for the arguments and/or value returned? For example, you might need versions of the same function that work with int, float and double data types. The most obvious way to do this is to use overloading, and explicitly define the required functions, all with the same name and content except for the data type.

An alternative is to use a template. This allows you to determine a function with a generic data type. For example:

template <class T>
T SumArray(T *array, int num)
{
   T my_sum = 0;
   for (int i=0; i<num; i++)
   {
      my_sum += array[i];
   }
   return(my_sum);
}


This is a very simple function that sums the first num values in an array. To use this for an integer array:

int arr[10];
int value = SumArray<int>(arr, 10);

Or you use it for doubles:

double arr[15];
double value = SumArray<double>(arr, 15);

This of course can be trivially extended to multiple data types, for example:

template <class T, class U>
double SumTwoArrays(T *array1, U *array2, int num1,
                    int num2)
{
   double my_sum = 0;
   for (int i=0; i<num1; i++)
   {
      my_sum += array1[i];
   }
   for (int i=0; i<num2; i++)
   {
      my_sum += array2[i];
   }
   return(my_sum);
}

Here a double is always returned by the function, but it has two input arguments, which can be of different types.

No comments: