![](/img/trans.png)
[英]template class specialization : template-id does not match any template declaration
[英]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.