模板特化错误 - C++(C++ Primer Plus练习)

2 c++ templates specialization

我目前正在学习C++,所以我对这个主题知之甚少.我正在使用C++入门加书,这就是问题所在:

编写一个模板函数maxn(),它将一个T类型的项数组作为参数,一个整数表示数组中元素的数量,并返回数组中最大的项.在程序中测试它,该程序使用函数模板,其中包含六个int值的数组和一个包含四个double值的数组.该程序还应包括一个特殊化,它将一个指向char的数组作为参数,指针的数量作为第二个参数,并返回最长字符串的地址.如果多个字符串被绑定为具有最长的长度,则该函数应返回第一个被绑定为最长的地址.使用五个字符串指针的数组测试特化.

这是我的代码:

#include <iostream>
#include <cstring>
using namespace std;

template <class T> T maxn(T arr[] , int n);
template <> char * maxn<char (*)[10]> (char (*arr)[10] , int n);

int main()
{
    double array[5] = { 1.2 , 4.12 ,7.32 ,2.1 ,3.5};
    cout << endl << maxn(array , 5) << endl << endl;

    char strings[5][6] = { "asta" , " m" , "ta" , "taree" , "e"};
    cout << maxn(strings , 5) << endl;

    return 0;
}

template <class T> T maxn(T arr[] , int n)
{
    T max = 0;
    for (int i = 0 ; i < n ; ++i)
    {
        if (arr[i] > max)
        max = arr[i];
    }
    return max;

}

template <> char * maxn<char (*)[10]> (char (*arr)[10] , int n)
{
    int length = 0;
    int mem = 0;
    for ( int i = 0 ; i < n ; ++i)
    {
        if (strlen(arr[i]) > length)
        {
            length = strlen(arr[i]);
            mem = i;
        }
    }
    return arr[mem];
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试传递一个字符串数组.我收到以下错误:

    g++ -Wall -o "untitled5" "untitled5.cpp" (in directory: /home/eukristian)
untitled5.cpp:6: error: template-id ‘maxn<char (*)[10]>’ for ‘char* maxn(char (*)[10], int)’ does not match any template declaration
untitled5.cpp: In function ‘int main()’:
untitled5.cpp:14: error: no matching function for call to ‘maxn(char [5][6], int)’
untitled5.cpp: At global scope:
untitled5.cpp:31: error: template-id ‘maxn<char (*)[10]>’ for ‘char* maxn(char (*)[10], int)’ does not match any template declaration
Compilation failed.
Run Code Online (Sandbox Code Playgroud)

我很确定我犯了一些新手的错误,我无法察觉.谢谢 .

sep*_*p2k 7

char (*)[10]是一个指向10个字符数组的指针.char *[10]是一个由10个char指针组成的数组.

如果函数应该返回char*,你还要为返回值指定一个不同的类型,T的值也应该是char*.您的专业化应如下所示:

template <> char * maxn<char *> (char *arr[] , int n);
Run Code Online (Sandbox Code Playgroud)

你的字符串数组也应该是类型char *[5].