没有与指定类型匹配的函数模板实例

No instance of function template matches the specified type

本文关键字:函数模板 实例 类型      更新时间:2023-10-16

我读过这可能是IntelliSense的问题,但我真的不知道这是真是假。当我编译代码时,我遇到了一个错误(标题),不知道如何修复它。我的书(Stephen Prata的《Sams C++Primer Plus》)没有解决我的问题。我写了一个非常相似的程序,但问题没有出现。

也许问题出在类型说明符上?它和模板的一样吗?真的很抱歉我的语言。。。

#include <iostream>
template <typename T>
T maxn(T tab[], int size);
template <> float maxn<float>(float, int); // Problem appears here...
int main()
{
    std::cin.get();
    return 0;
}
template <typename T>
T maxn(T tab[], int size)
{
    T max = tab[0];
    for (int i = 1; i < size; i++)
    {
        if (tab[i] > max) max = tab[i];
    }
}

我很感激你的建议。谢谢

特殊化的第一个参数不正确。您给出了float,但根据模板,它应该是一个浮点数组。

template <> float maxn<float>(float[], int);
//                                 ^
// You need to indicate that the first parameter is an array.

请注意,您没有为专门化声明主体,因此如果您尝试使用它,链接将失败。(除非您在另一个编译单元中提供实现。)