jte*_*dit 13 c++ variables static templates class
如果你有一个带有静态变量的模板类,有没有办法让变量在所有类的类中相同,而不是每个类都相同?
目前我的代码是这样的:
template <typename T> class templateClass{
public:
static int numberAlive;
templateClass(){ this->numberAlive++; }
~templateClass(){ this->numberAlive--; }
};
template <typename T> int templateClass<T>::numberAlive = 0;
Run Code Online (Sandbox Code Playgroud)
主要:
templateClass<int> t1;
templateClass<int> t2;
templateClass<bool> t3;
cout << "T1: " << t1.numberAlive << endl;
cout << "T2: " << t2.numberAlive << endl;
cout << "T3: " << t3.numberAlive << endl;
Run Code Online (Sandbox Code Playgroud)
这输出:
T1: 2
T2: 2
T3: 1
Run Code Online (Sandbox Code Playgroud)
所期望的行为在哪里:
T1: 3
T2: 3
T3: 3
Run Code Online (Sandbox Code Playgroud)
我想我可以使用某种类型的全局int来实现它,任何类型的此类递增和递减,但这看起来不合逻辑,或者面向对象
谢谢任何可以帮助我实现这一点的人.
Oli*_*rth 30
让所有类派生自一个公共基类,其唯一的责任是包含静态成员.
class MyBaseClass {
protected:
static int numberAlive;
};
template <typename T>
class TemplateClass : public MyBaseClass {
public:
TemplateClass(){ numberAlive++; }
~TemplateClass(){ numberAlive--; }
};
Run Code Online (Sandbox Code Playgroud)