Planeshift

singleton.h

Go to the documentation of this file.
00001 /*
00002  * singleton.h - Author: Andrew Dai
00003  *
00004  * Copyright (C) 2004 Atomic Blue ([email protected], http://www.atomicblue.org) 
00005  *
00006  *
00007  * This program is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU General Public License
00009  * as published by the Free Software Foundation (version 2 of the License)
00010  * This program is distributed in the hope that it will be useful,
00011  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00012  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00013  * GNU General Public License for more details.
00014  * You should have received a copy of the GNU General Public License
00015  * along with this program; if not, write to the Free Software
00016  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
00017  */
00018 
00019 #ifndef __SINGLETON_H__
00020 #define __SINGLETON_H__
00021 
00026 template <typename T> class Singleton
00027 {
00028     static T* ptrSingleton;
00029     
00030 public:
00031     Singleton(T* ptr)
00032     {
00033         CS_ASSERT(ptrSingleton == 0);
00034         ptrSingleton = ptr;
00035     }
00036 
00037     // Use this constructor only when the derived class is only deriving from Singleton
00038     Singleton(void)
00039     {
00040         CS_ASSERT(ptrSingleton == 0);
00041         ptrSingleton = (T*) (this);
00042     }
00043 
00044     ~Singleton()
00045     {
00046         CS_ASSERT(ptrSingleton != 0);
00047         ptrSingleton = NULL;
00048     }
00049     static T& GetSingleton(void)
00050     {
00051         return *ptrSingleton;
00052     }
00053     static T* GetSingletonPtr(void)
00054     {
00055         return ptrSingleton;
00056     }
00057 };
00058 template <typename T> T* Singleton<T>::ptrSingleton = 0;
00059 
00062 #endif
00063