在通用类的模板定义中,也可以使用标准类型的参数。也就是说,在模板的定义中,你可以指定标准类型参数。
测试代码:
[C++] 纯文本查看 复制代码 #include <iostream>
#include <cstdlib>
using namespace std;
//size 是一个标准类型的参数
template <class AType, int size> class atype
{
AType a[size]; //通过参数 size 传递数组的长度
public:
atype()
{
register int i;
for (i = 0; i < size; i++)
a[i] = i;
}
AType &operator[] (int i);
};
//为 atype 类型的对象提供边界检测
template <class AType, int size> AType &atype<AType, size>::operator[](int i)
{
if (i < 0 || i > size-1) {
cout << "\nIndex value of ";
cout << i << " is out-of-bounds.\n";
exit(1);
}
return a[i];
}
int main()
{
atype<int, 10> intob; //大小为10的整数数组对象
atype<double, 15> doubleob; //大小为15的double数组对象
int i;
cout << "Integer array: ";
for (i = 0; i < 10; i++)
intob[i] = i;
for (i = 0; i < 10; i++)
cout << intob[i] << " ";
cout << '\n';
cout << "Double array: ";
for (i = 0; i < 15; i++)
doubleob[i] = (double) i/3;
for (i = 0; i < 15; i++)
cout << doubleob[i] << " ";
cout << '\n';
return 0;
}
运行输出:Integer array: 0 1 2 3 4 5 6 7 8 9
Double array: 0 0.333333 0.666667 1 1.33333 1.66667 2 2.33333 2.66667 3 3.33333 3.66667 4 4.33333 4.66667 说明:
在 atype 模板定义中,参数 size 被声明为 int 类型,它用来指定数组 a 的大小。尽管 size 在源代码中是一个“变量”,但她的值是在编译时得到的,这样就可以用来设置数组的大小。
在模板定义中使用的参数的标准类型仅限于整数类型,指针类型或者引用类型,而其它的数据类型(如 float)是不允许作为模板定义中参数的标准类型的。传递给模板的实际参数必须要么包含一个整数常量,要么包含一个全局函数或全局对象的指针或引用。也就是说,由于标准类型参数的值不能被改变,所以标准类型参数也就可以认为是常量。
比如下面代码:
[C++] 纯文本查看 复制代码 #include <iostream>
using namespace std;
template <class Atype, float size> class atype
{
public:
atype() {
cout << size << endl;
}
};
int main()
{
atype<int, 100> a;
return 0;
}
注意,在上面的模板类的定义中,故意将 int size 改成 float size 后,编译器会发出错误信息:temp.cc:5:30: error: ‘float’ is not a valid type for a template constant parameter
temp.cc: In constructor ‘atype<Atype, <declaration error> >::atype()’:
temp.cc:9:11: error: ‘size’ was not declared in this scope
temp.cc: In function ‘int main()’:
temp.cc:15:16: error: ‘<type error>’ is not a valid type for a template constant parameter
temp.cc:15:19: error: invalid type in declaration before ‘;’ token
又如我们将上面的 size 进行赋值操作:
[C++] 纯文本查看 复制代码 template <class Atype, int size> class atype
{
public:
atype() {
cout << size << endl;
size = 200;
cout << size << endl;
}
};
编译时会看到下面的错误提示:temp.cc: In constructor ‘atype<Atype, size>::atype() [with Atype = int, int size = 100]’:
temp.cc:17:18: instantiated from here
temp.cc:10:3: error: lvalue required as left operand of assignment 从上面的提示信息知道:左值需要为其分配一个左操作数。由此可见,size 并不是一个合适的左操作数,正如上面所讲,它是一个常量,而常量是不能给它赋值的。
由于标准类型参数可以看做是常量,所以他们可以用来设置数组的大小,这是一个很实在的好处。 |