为什么在这里调用模板而不是指针指向数组的特化?
#include<iostream>
#include<cstring>
using namespace std;
// Compute the maximum of 5 T's
template <typename T> T maxn(T[], int n);
template <> char* maxn(char*[], int n);
int main() {
int ints[4] = { 1, 2, 3, 4 };
cout << "max of ints is " << maxn(ints, 4) << endl;
const char* abcs[] = {"a", "bee", "c"};
cout << "longest word of palindrome is " << maxn(abcs, 3) << endl;
return 0;
}
// Compute the maximum of an array of T's
template <typename T> T maxn(T arr[], int n) {
T max = arr[0];
for (int i = 1; i < n; i++) {
T t = arr[i];
if (t > max) max = t;
}
return max;
}
// Compute the longest word
template <> char* maxn(char* ca[], int n) {
char* longest = ca[0];
int len = strlen(ca[0]);
for (int i = 1; i < n; i++) {
cout << ca[i] << endl;
int l = strlen(ca[i]);
if (l > len) {
cout << "Found a longer one." << endl;
longest = ca[i];
len = l;
}
}
return longest;
}
// Output:
// max of ints is 4
// longest word of palindrome is c
专业化中的类型信息似乎更具体,因此g ++更愿意这样做。