繁体   English   中英

显式特化 - 模板 ID 不匹配任何模板声明

[英]Explicit specialization - template-id does not match any template declaration

我对 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*或者专攻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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM