#include <assert.h> template <typename T> class Singleton { protected: static T* ms_Singleton; public: Singleton( void ) { assert( !ms_Singleton ); ms_Singleton = static_cast<T*>(this); } ~Singleton( void ) { assert( ms_Singleton ); ms_Singleton = 0; } static T& getSingleton( void ) { assert( ms_Singleton ); return ( *ms_Singleton ); } static T* getSingletonPtr( void ) { return ( ms_Singleton ); } private: Singleton& operator=(const Singleton&) { return this; } Singleton(const Singleton&) {} }; #include "singleton.h" class Test : public Singleton<Test> { public: Test() { } void Print() { printf("test/n");} ~Test(){} }; class Test1 : public Singleton<Test1> { public: Test1() { } void Print() { printf("test1/n");} ~Test1(){} }; template<> Test* Singleton<Test>::ms_Singleton = 0; template<> Test1* Singleton<Test1>::ms_Singleton = 0; void CreateSingleton() { new Test(); new Test1(); } void DestroySingleton() { delete Test::getSingletonPtr(); delete Test::getSingletonPtr(); } int _tmain(int argc, _TCHAR* argv[]) { CreateSingleton(); Test::getSingletonPtr()->Print(); Test1::getSingletonPtr()->Print(); DestroySingleton(); return 0; }