C++ 具有静态成员的模板类 - 对于类的所有类型的类都相同
C++ Template Class with Static Members - Same for all types of the class
如果你有一个带有静态变量的模板类,有没有办法让变量在所有类型的类中都相同,而不是每个类型都相同?
目前我的代码是这样的:
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--; }
};
相关文章:
- 调用具有未标识类型的类的方法
- C++ 中模板化类型的类层次结构
- 如何添加依赖于类本身的模板成员变量
- 为什么同时覆盖全局新运算符和特定于类的运算符不是模棱两可的行为?
- 根据模板类型选择类模板的成员类型?
- C++从抽象类型定义类成员
- 实例化具有不完整类型的类模板格式不正确(如果该类型是在之后定义的)
- 依赖于类成员属性的类实例成员
- 重载模板<类型名...>类的函数模板
- 在设计方面:重载vector类型的类成员的插入运算符
- 错误:使用 SWIG 的未知类型名称"类"
- 添加字符串类型的类成员会导致调用基类函数而不是子函数
- 包装任意类型/非类型模板类的模板类
- 使用相同方法但不同成员类型构建类的最佳方法
- 如何删除类内类类型的类成员指针
- 为什么我不能在同一行中定义两个相同类型的类的成员指针
- 为什么 std::vector 适用于类定义中的不完整类型?
- 如何在未评估的上下文中将成员函数的结果类型应用于类成员
- 我该如何文档文档以使文档适用于类成员而不是匿名类型
- 使用依赖于类的类型和函数,在类的所有实例中具有相同值的c++变量