类模板里可以有static成员,当类模板被模板实参实例化后,这个static成员也会被实例化,并且被该实例类型的所有对象共享。

1
2
3
4
5
6
7
8
9
10
11
template<typename T>
class MyClass
{
public:
static int id;
static int GetID() { return id; }
};

// 不要忘了类外定义
template<typename T>
int MyClass<T>::id = 0;

如果此时生成一个MyClass<int>实例类类型,那么这两个static成员就被全部的类型为MyClass<int>的对象共享

1
2
3
4
5
6
7
MyClass<int> test_MyClass;
std::cout << test_MyClass.GetID() << std::endl;
MyClass<int>::id = 1919810;
std::cout << MyClass<int>::GetID() << std::endl;

// 这种是不对的
MyClass::GetID(); // 缺少类模板`MyClass`的参数列表