C++中有一个重要特性,那就是模板类型。类似于Objective-C中的泛型。C++通过类模板来实现泛型支持。
在引入typename之前,class关键字早已在模板申明中被使用。在typename关键字引入后,可以用它来替代class关键字。
如:template<class T1, class T2> 和 template<typename T1, typename T2>相同
1.普通的模板类:
1)定义一个temp的模板类:
template<class T>
class temp
{
public:
temp();
temp(T k);
~temp(){}
void print();
T operator+(T j);
private:
T m;
const T i;
};
2)相关函数的实现
template<class T>
temp<T>::temp()
{
i = 0;
m = 0;
}
template<class T>
temp<T>::temp(T k) :i(k), m(k)
{
}
template<class T>
void temp<T>::print()
{
cout << "n=" << m << endl;
cout << "i=" << i << endl;
}
template<class T>
T temp<T>::operator+(T j)
{
return m + j;
}
3)主函数
int main()
{
temp<int> t(1);
t.print();
cout << t + 1 << endl;
system("pause");
return 0;
}
输出:
2.在模板类中加入静态成员
template<class T>
class temp
{
public:
temp();
temp(T k);
~temp(){}
void print();
T operator+(T j);
static int count; //静态成员变量
private:
T m;
const T i;
};
template<class T> int temp<T>::count = 0; //赋值
3.在模板类中加入模板函数
template<class T>
class STR
{
public:
template<class T2>int compare(const T2&);
...
};
template<class T>template<class T2>int STR<T>::compare(const T2& s)
{
...
}
4.友元模板
template<class T>
class STR
{
public:
template<class T2>int compare(const T2&);
friend<class Type>friend class A;
template<class Type>friend void D(B<Type>);
template<class Type>friend void C::Cf();
};