[英]Explicit specialization - template-id does not match any template declaration
I have a problem regarding explicit specialization in C++ program我对 C++ 程序中的显式专业化有疑问
I want to make a specialization for char* type that returns an address to the longest char array but i keep getting errors :我想对 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|
Here is the code to the program这是程序的代码
#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;
}
I haven't implemented the function yet but it has been declared.我还没有实现这个功能,但它已经被声明了。 Also i suppose that it would be easier to use function overload but it is an assigment from a book.
此外,我认为使用函数重载会更容易,但它是书中的一个分配。
Thanks for answers in advance.感谢您提前回答。
Your template returns the type T
and takes a type T*
but your specialization returns the same type as it takes, so it doesn't match.您的模板返回类型
T
并采用类型T*
但您的专业化返回的类型与其所采用的类型相同,因此它不匹配。
If you specialize for T=char*
, then it needs to take a T* (char**) and return a char*
or instead specialize on char
如果你专攻
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.