先来个模板的随便使用
template<typename Type, size_t _N=8>
class SeqList
{
public:
SeqList(int sz = SZ_SZIE)
{
capacity = sz > SZ_SIZE ? sz : SZ_SIZE;
base = new Type[capacity];
size = 0;
}
private:
enum{SZ_SIZE = 8};
private:
Type* base;
size_t capacity;
size_t size;
};
void main()
{
SeqList<int,100> list(10);
}
但是模板也会出现问题,例如返回等于,传的参数是字符串,则等于会匹配成地址的等于号所以有了这样子是错误的
//类的模板特化泛化
template<class T1,class T2>
class Data
{
public:
Data()
{
cout << "Data<T1,T2>" << endl;
}
private:
T1 d1;
T2 d2;
};
//得先有泛化 才会有偏特化,全特化 必须有泛化
//全特化
template<>
class Data<int, char>
{
public:
Data()
{
cout << "Data<int,char>" << endl;
}
private:
int d1;
char d2;
};
//偏特化
template<class T>
class Data<T, T>
{
public:
Data()
{
cout << "Data<T11,T22>" << endl;
}
private:
T d1;
T d2;
};
template<class T>
class Data<T, int>
{
public:
Data()
{
cout << "Data<T,int>" << endl;
}
private:
T d1;
T d2;
};
template<class T1,class T2>
class Data<T1*, T2*>
{
public:
Data()
{
cout << "Data<T1*,T2*>" << endl;
}
private:
T1 d1;
T2 d2;
};
void main()
{
Data <int*, char*> dt;
Data<int, char> dt1;
Data<char, char> dt2;
Data<char*, int*> dt3;
}
同样的,必须有泛化才会有特化!