我对 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/