C++ 具有静态成员的模板类 - 对于类的所有类型的类都相同

C++ Template Class with Static Members - Same for all types of the class

本文关键字:类型 于类 C++ 静态成员      更新时间:2023-10-16

如果你有一个带有静态变量的模板类,有没有办法让变量在所有类型的类中都相同,而不是每个类型都相同?

目前我的代码是这样的:

 template <typename T> class templateClass{
 public:
     static int numberAlive;
     templateClass(){ this->numberAlive++; }
     ~templateClass(){ this->numberAlive--; }
};
template <typename T> int templateClass<T>::numberAlive = 0;

和主要:

templateClass<int> t1;
templateClass<int> t2;
templateClass<bool> t3;
cout << "T1: " << t1.numberAlive << endl;
cout << "T2: " << t2.numberAlive << endl;
cout << "T3: " << t3.numberAlive << endl;

这输出:

 T1: 2
 T2: 2
 T3: 1

其中,所需的行为是:

 T1: 3
 T2: 3
 T3: 3

我想我可以用某种全局 int 来做到这一点,任何类型的此类都会递增和递减,但这似乎不是很合乎逻辑,或者面向对象

感谢任何可以帮助我实现这一点的人。

让所有类都派生自一个公共基类,其唯一职责是包含静态成员。

class MyBaseClass {
protected:
    static int numberAlive;
};
template <typename T>
class TemplateClass : public MyBaseClass {
public:
    TemplateClass(){ numberAlive++; }
   ~TemplateClass(){ numberAlive--; }
};