需求:有时遇到某些类特征相似而又没有共同的父类,希望能够知道这些类的创建数量之和。
思路:将这些类继承自同一个计数类,共享计数变量s_createCount信息,实现如下:
class Counter
{
public:Counter() {++s_createCount;++s_aliveCount;std::cout << "Class Created Count = " << s_createCount << " Class Alive Count = " << s_aliveCount << std::endl;}~Counter() {--s_aliveCount;std::cout << "Class Alive Count = " << s_aliveCount << std::endl;}private:static int s_createCount;static int s_aliveCount;
};int Counter::s_createCount = 0;
int Counter::s_aliveCount = 0;class CounterA : public Counter{};
class CounterB : public Counter {};int main()
{CounterA ca;CounterB cb;{CounterA ca2;}system("pause");return 0;
}
需求:有时遇到某些类,希望能够分别知道各个类的创建数量信息(兼容需求1)。
思路:既然继承同一个类会导致共享静态数据,那么可以依靠类模板的特性(只要模板参数不同,类就不同),继承不同的类,实现如下:
template <typename T>
class Counter
{
public:Counter() {++s_createCount;++s_aliveCount;std::cout << __FUNCTION__ << "Class Created Count = " << s_createCount << " Class Alive Count = " << s_aliveCount << std::endl;}~Counter() {--s_aliveCount;std::cout << __FUNCTION__ << "Class Alive Count = " << s_aliveCount << std::endl;}private:static int s_createCount;static int s_aliveCount;
};template <typename T>
int Counter<T>::s_createCount = 0;
template <typename T>
int Counter<T>::s_aliveCount = 0;// 这里不必考虑CRTP易错点(兼容需求1):派生的基类模板参数不是派生类
// 允许class CounterB : public Counter<CounterA> {};的情况存在
// 因为不涉及将模板参数T转换为派生类的操作
class CounterA : public Counter<CounterA> {};
class CounterB : public Counter<CounterB> {};int main()
{CounterA ca;CounterB cb;CounterC cc;{CounterA ca2;}system("pause");return 0;
}