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

标签 c++ templates specialization

我目前正在学习 C++,所以我对这个主题的了解不多。我正在使用 C++ primer plus 书,这就是问题所在:

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

这是我的代码:

#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];
}

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

    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.

我很确定我犯了一些新手错误,但我无法检测到它。 谢谢。

最佳答案

char (*)[10] 是指向 10 个字符数组的指针。 char *[10] 是一个包含 10 个字符指针的数组。

此外,您还为返回值指定了与 T 不同的类型。如果函数应该返回 char*,则 T 的值也应该是 char*。您的专业应该如下所示:

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

此外,您的字符串数组应为 char *[5] 类型。

关于c++ - 模板特化错误 - C++(C++ Primer Plus 练习),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1427457/

相关文章:

c++ - 谁负责 futures 和 promises 的共享状态

C++使用SFINAE检测任何构造函数

c++ - 未解析的重载函数类型

c++ - 作为模板类型参数,为什么 type[N] 不匹配其专用版本---- template<class T> class S<T[]>

c++ - 在 Visual Studio 2019 C++ 中,如何扩展动态分配的数组以显示其所有元素?

c++ - 独立的事物相互影响(我不知道发生了什么)

c++ - 区分字符串文字和字符数组

c++ - 模板类中特殊函数的声明

c++ - 函数模板显式特化 C++

c++ - 你能将整个网页嵌入到 C++ 源代码中吗?