00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00013
00014 #ifndef SGSINGLETON_H_
00015 #define SGSINGLETON_H_
00016
00017 #include <cassert>
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039
00040
00041 #ifdef _WIN32
00042 #pragma warning( push )
00043 #pragma warning( disable:4311 ) // 'variable' : pointer truncation from 'type' to 'type'
00044 #pragma warning( disable:4312 ) // 'variable' : conversion from 'type' to 'type' of greater size
00045 #endif
00046
00047 template <typename T>
00048 class Singleton
00049 {
00050 static T* m_pInstance;
00051 public:
00052
00053 Singleton()
00054 {
00055 assert( !m_pInstance );
00056 int offset = reinterpret_cast<int>( reinterpret_cast<T*>( 0x1 ) ) - reinterpret_cast<int>( reinterpret_cast< Singleton<T>* >( reinterpret_cast<T*>( 0x1 ) ) );
00057 m_pInstance = reinterpret_cast<T*>(reinterpret_cast<int>(this) + offset);
00058 }
00059
00060 virtual ~Singleton()
00061 {
00062 assert(m_pInstance);
00063 m_pInstance = 0;
00064 }
00065
00066 static T& Get() { assert(m_pInstance); return *m_pInstance; }
00067 static T* GetPtr() { assert(m_pInstance); return m_pInstance; }
00068
00069 private:
00070
00071 Singleton(const Singleton&) {}
00072
00073
00074 };
00075
00076 template <typename T> T* Singleton <T>::m_pInstance = 0;
00077
00078 #ifdef _WIN32
00079 #pragma warning(pop)
00080 #endif
00081
00082
00083 #endif