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:
Post a Comment