问题
I am writing a program that requires a template function having an array of items, and number of items in that array as arguments. The function needs to return the largest item in said array. The program should also have a specialization (what I'm having issues with) which checks for the longest string in the array, if an array of strings is entered.
Here are my prototypes:
template <typename T>
T compare(T const arr1[], int n);
template <> const char *compare<const char *>(const char *const arr2[][3], int n);
main program..
int main()
{
int a[7] = { 3, 67, 100, 91, 56, 67, 83 };
double b[] = { 2.5, 2.6102, 2.61, 1.03 };
//char* c[3] = { "see if this works", "functions", "explicit specialization" };
char c0[30] = { "see if this works" };
char c1[30] = { "functions" };
char c2[30] = { "explicit specialization" };
char *d[][3] = { c0, c1, c2 };
cout << "Comparing int values: " << endl;
cout << "Largest int value is: " << compare(a, 7) << endl;
cout << "Comparing double values: " << endl;
cout << "Largest double value is: " << compare(b, 4) << endl;
return 0;
}
function definition...
template <typename T>
T compare(T const arr1[], int n) {
T temp;
........
return temp;
}
template <> const char *compare<const char *>(const char *const arr2[][3], int n); {
const char *temp2 = &arr2[0];
return *temp2;
}
I wrote some dummy code to test whether the second function works but it does not return the correct value (it returns 'explicit specialization') Can someone please point out to me what's wrong with the syntax?
回答1:
As said above, an overload is much more suited to this problem than a specialization:
const char *compare(const char *const arr2[], int n);
Note that while I put the square brackets into the parameter type to match the template, this declaration is equivalent to one with const char *const *arr2
because function parameters are special in this regard.
Assuming you absolutely require a specialization for whatever reason (although the explanation can also apply to the above solution):
Consider what T
is and what your specialization is for. T
is the element type of the sequence and you've specialized your template for T=char
. This means that you've specialized your template for a sequence of characters, not a sequence of strings.
To specialize for a sequence of C strings, substitute const char *
for T
rather than char
:
template <> const char *compare<const char *>(const char *const arr2[], int n);
来源:https://stackoverflow.com/questions/33860944/explicit-specialization-syntax-error