Skip to content

Instantly share code, notes, and snippets.

@Drusy
Created March 19, 2014 21:09
Show Gist options
  • Save Drusy/9651355 to your computer and use it in GitHub Desktop.
Save Drusy/9651355 to your computer and use it in GitHub Desktop.
Generic C++ singleton implementation
#ifndef SINGLETON_H
#define SINGLETON_H
#include <string>
using namespace std;
template<typename T>
class Singleton
{
public:
static bool isBuilt();
static T* instance();
protected:
static T* _instance;
static void buildInstance();
Singleton(){}
~Singleton(){}
};
template<typename T>
T* Singleton<T>::_instance = 0;
template<typename T>
void Singleton<T>::buildInstance()
{
if ( _instance )
throw "Singleton already constructed";
_instance = new T();
}
template<typename T>
T* Singleton<T>::instance() {
if ( ! isBuilt() )
buildInstance();
return _instance;
}
template<typename T>
bool Singleton<T>::isBuilt() {
return (_instance != 0);
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment