#include <assert.h>
#include <iostream.h>
template <typename T> class Singleton
{
static T* ms_Singleton;
public:
Singleton( void )
{
assert( !ms_Singleton );
int offset = (int)(T*)1 - (int)(Singleton <T>*)(T*)1;
ms_Singleton = (T*)((int)this + offset);
cout<<"ok1"<<endl;
}
~Singleton( void )
{ assert( ms_Singleton ); ms_Singleton = 0; }
static T& GetSingleton( void )
{
if ( 0 == ms_Singleton )
{
ms_Singleton = new T;
}
assert( ms_Singleton );
return ( *ms_Singleton );
}
static T* GetSingletonPtr( void )
{ return ( ms_Singleton ); }
};
template <typename T> T* Singleton <T>::ms_Singleton = 0;
// Sample usage:
//
class TextureMgr : public Singleton <TextureMgr>
{
public:
TextureMgr * GetTexture( const char* name );
// ...
};
TextureMgr * TextureMgr::GetTexture( const char* name )
{
return 0;
}
#define g_TextureMgr TextureMgr::GetSingleton()
void SomeFunction( void )
{
TextureMgr * stone1 = TextureMgr::GetSingleton().GetTexture( "stone1" );
TextureMgr * wood6 = g_TextureMgr.GetTexture( "wood6" );
// ...
}
void main()
{
cout<<"ok2"<<endl;
SomeFunction();
return;
}