1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
#include <iostream>
#include <cstring>
using std::cout;
using std::endl;
template <typename T>
T maxn(T arr[], int size); // template prototype for the maxn function
template <> char* maxn<char*>(char* cp_arr[], int size); // specialization prototype for the array of pointers
int main()
{
int n_arr[] = {1, 2, 3, 4, 5, 6};
double d_arr[] = {1.1, 2.2, 3.3, 4.4};
char cp1[] = "Hi!";
char cp2[] = "A string!";
char cp3[] = "This is a bigger string1!";
char cp4[] = "This is a bigger string2!";
char* cp_arr[] = {cp1, cp2, cp3, cp4};
int n_max = maxn(n_arr, 6);
double d_max = maxn(d_arr, 4);
char* cp_max = maxn(cp_arr, 4);
cout << "Int max is:"
<< n_max
<< endl
<< "Double max is:"
<< d_max
<< endl
<< "Biggest string is:"
<< cp_max
<< endl;
return 0;
}
template <typename T>
T maxn(T arr[], int size)
{
T max = arr[0];
for (int i = 1; i < size; i++)
{
if (max < arr[i])
max = arr[i];
}
return max;
}
template <> char* maxn<char*>(char* cp_arr[], int size)
{
char* cp_max = cp_arr[0];
for (int i = 1; i < size; i++)
{
if (strlen(cp_max) < strlen(cp_arr[i]))
cp_max = cp_arr[i];
}
return cp_max;
}
|