C++:CRTP奇特的递归模板模式

/ C++ / 没有评论 / 1965浏览

demo:

## 实现对象的计数
template<typename T>
struct counter
{
	counter()
	{
		objects_created++;
		objects_alive++;
	}

	virtual ~counter()
	{
		--objects_alive;
		--objects_created;
	}

	static int objects_created;
	static int objects_alive;
};

template<typename T>
int counter<T>::objects_created(0);

template<typename T>
int counter<T>::objects_alive(0);

class Obj : public counter<Obj>
{
public:
	Obj()
	{

	}
	~Obj()
	{

	}
	void print()
	{
		cout << "sss" << endl;
	}
};

int main()
{
	Obj obj;
	cout << Obj::objects_created << endl;
	cout << Obj::objects_alive << endl;
	obj.~Obj();
	cout << Obj::objects_created << endl;
	cout << Obj::objects_alive << endl;
	
	return 0;
}