函数模板具体化出错报错说找不多匹配的声明
嘿碳头 2017-08-16 10:35:46 #include<iostream>
#include<iomanip>
#include<cstring>
using namespace std;
class CName
{
char *name;
public:
CName(char* str=NULL)
{
if(str) { name=new char [strlen(str)+1]; strcpy(name,str);}
}
~CName()
{
if(name){ delete [] name; name=NULL;}
}
void SetName(char* str)
{
if(name){delete [] name; name=NULL;}
if(str){name=new char [strlen(str)+1]; strcpy(name,str);}
}
char* GetName(void)
{
return name;
}
void print()
{
cout<<name<<endl;
}
};
template <class T, int ID>
void myswap(T &a, T &b)
{
T temp;
temp=a; a=b; b=temp;
cout<<"调用引用参数的函数模板!ID="<<ID<<endl;
}
template<>
void myswap<CName,int>(CName &a, CName &b)//编译报错 找不到匹配的函数模板声明
{
char *temp=new char[strlen(a.GetName())+1];
strcpy(temp,a.GetName());
a.SetName(b.GetName());
b.SetName(temp);
delete [] temp;
cout<<"调用CName引用参数的模板函数"<<endl;
}
template <class T,int ID>
void myswap(T *a, T *b)
{
T temp;
temp=*a; *a=*b; *b=temp;
cout<<"调用指针参数的函数模板!ID="<<ID<<endl;
}
template<>
void myswap<CName,int>(CName *a, CName *b)//编译报错 找不到匹配的函数模板声明
{
char *temp=new char [strlen(a->GetName())+1];
strcpy(temp,a->GetName());
a->SetName(b->GetName());
b->SetName(temp);
cout<<"调用CName的指针参数的模板函数!"<<endl;
}
int main()
{
int a=8,b=10;
myswap<int,3>(a,b);
myswap<int,3>(&a,&b);
CName one((char*)"Ding");
CName two((char*)"ZHANG");
// one.print();
// two.print();
myswap<CName,1>(one,two);
myswap<CName,1>(&one,&two);
myswap<CName,2>(one,two);
myswap<CName,2>(&one,&two);
// one.print();
// two.print();
return 0;
}