每种不同类型的模板函数,其静态变量不共享
例子如下:
template<typename T>
void useOfStatic(const T& A) {
static int i = 0;
cout << ++i << endl;
}
int main() {
useOfStatic<int>(10);
useOfStatic<int>(20);
useOfStatic<double>(2.5);
system("PAUSE");
return 0;
}
输出结果如下:
1
2
1
类模板的静态变量与函数模板类似:
//模板类同理
template<class T>
class templateClassUse {
private:
T x;
public:
static int testi;
templateClassUse()
{
cout << ++testi << endl;
}
};
template<class T>
int templateClassUse<T>::testi = 0; //类中静态对象的初始化
使用:
templateClassUse<int> a;
templateClassUse<int> b;
templateClassUse<char> c;
templateClassUse<char> d;
templateClassUse<char> e;
输出:
1
2
3
4
5
结论:不同类型的模板类或模板函数不共享静态变量