c++ - 显式特化 - template-id 与任何模板声明都不匹配

标签 c++ c++11 templates specialization explicit

我对 C++ 程序的显式特化有疑问

我想对 char* 类型进行专门化,它返回最长 char 数组的地址,但我不断收到错误:

C:\Users\Olek\C++\8_1\main.cpp|6|error: template-id 'maxn<char*>' for 'char* maxn(char*)' does not match any template declaration|
C:\Users\Olek\C++\8_1\main.cpp|38|error: template-id 'maxn<char*>' for 'char* maxn(char*)' does not match any template declaration|

这是程序代码

#include <iostream>

template <typename T>
T maxn(T*,int);

template <> char* maxn<char*>(char*);

const char* arr[5]={
    "Witam Panstwa!",
    "Jak tam dzionek?",
    "Bo u mnie dobrze",
    "Bardzo lubie jesc slodkie desery",
    "Chociaz nie powinienem",
};

using namespace std;

int main()
{
    int x[5]={1,4,6,2,-6};
    double Y[4]={0.1,38.23,0.0,24.8};
    cout<<maxn(x,5)<<endl;
    cout<<maxn(Y,4)<<endl;
    return 0;
}

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

template <>
char* maxn<char*>(char* ch){
    return ch;
}

我还没有实现该功能,但它已经被声明了。另外我认为使用函数重载会更容易,但这是书上的分配。

感谢您的提前答复。

最佳答案

您的模板返回类型 T 并采用类型 T*,但您的特化返回的类型与其采用的类型相同,因此不匹配。

如果您专门针对 T=char*,那么它需要采用 T* (char**) 并返回 char* 或专门针对 字符

template <typename T>
T maxn(T*,int);

template <> char maxn<char>(char*, int);
template <> char* maxn<char*>(char**, int);

int main() {
    char * str;
    maxn(str, 5);
    maxn(&str, 6);
}

关于c++ - 显式特化 - template-id 与任何模板声明都不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45265390/

相关文章:

C++ - 读取 3D 模型

c++ - 热衷于在专门的模板代码中初始化静态常量成员?

c++ - 如何将 mpl::set 的内容扩展为函数模板的模板参数

c++ - 模板会抛出很多错误

c++ - 尝试制作 STL map 容器的包装器时出错

c++ - Qt 从布局中取出一个小部件,但保持当前位置

c++ - 如何在cmake中为目标添加递归编译定义

c++ - 如何复制文件并继承Windows EFS?

c++ - 如何在函数返回期间将 move 语义与 std::string 一起使用?

c++ - 使用 `class` 关键字后跟未声明的标识符