MAXSIZE是新加入的第二个模板参数,类型为int,它指定了数组最多可包含的栈元素的个数
同样,我们可以为模板参数指定缺省值:
template
class Stack {
...
};
非类型的函数模板参数
你也可以为函数模板定义非类型参数。例如:
template
T addValue(T const& x)
{
return x + VAL:
}
借助于STL,可以传递这个函数模板的实例化给集中的每一个元素,让他们都增加一个整数值:
std::transform(source.begin(), source.end(), dest.begin(), (int(*)(int const&))addValue);
非类型模板参数的限制
非类型模板参数是有限制的 ,通常而言,它们可以是常整数(包括枚举值)或者指向外部链接对象的指针。
浮点数和类对象是不允许作为非类型模板参数的:
template
double process(double v) //error
{
return V * VAT;
}
template //error
class MyClass {
...
};
另外,你也不能使用全局指针作为模板参数 :
template
class MyClass{
...
};
char const* s = "hello";
MyClass x; //s是一个指向内部连接对象的指针
但是你可以这样使用:
template
class MyClass {
...
};
extern char const s[] = "hello";
MyClass x; //OK
全局字符数组s由"hello"初始化,是一个外部链接对象