1

ここで文字へのポインタの配列の特殊化の代わりにテンプレートが呼び出されるのはなぜですか?

#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++ はそれを好みます。

4

0 に答える 0