类模板的实例化必须由程序员在程序中显式地制定。
定义模板类对象的格式:
<类模板名><类型实参表><对象名>[(<实参表>)]
举个栗子:
#include <iostream>
using namespace std;
const int size = 10;
template<typename AType>
class atype
{
public:
atype()
{
for (int i = 0; i < size; i++) {
array[i] = i;
}
}
AType &operator[](int n);
private:
AType array[size];
};
template<typename AType>
AType &atype<AType>::operator[](int n)
{
if (n < 0 || n >= size) {
cout << "下标" << n << "超出范围" << endl;
exit(1);
}
return array[n];
}
int main()
{
atype<int> intob;
atype<double> doubleob;
cout << "Double数组:";
for (int i = 0; i < size; ++i)
doubleob[i] = (double) i / 2;
for (int i = 0; i < size; ++i)
cout << doubleob[i] << " ";
cout << endl;
intob[12] = 100;
return 0;
}
运行结果:
Double数组:0 0.5 1 1.5 2 2.5 3 3.5 4 4.5
下标12超出范围