// Copyright (C) 2012-2013 ChaosForge / Kornel Kisielewicz // http://chaosforge.org/ // // This file is part of NV Libraries. // For conditions of distribution and use, see copyright notice in nv.hh /** * @file singleton.hh * @author Kornel Kisielewicz epyon@chaosforge.org * @brief singleton pattern */ #ifndef NV_SINGLETON_HH #define NV_SINGLETON_HH #include namespace nv { template class singleton { private: static T *singleton_; protected: singleton() { assert(!singleton_); singleton_ = static_cast(this); } ~singleton() { assert(singleton_); singleton_ = 0; } public: static bool is_valid() { return singleton_ != 0; } static T *pointer() { assert(singleton_); return singleton_; } static T &reference() { assert(singleton_); return *singleton_; } }; template T* singleton::singleton_ = 0; template class auto_singleton : public singleton { public: static T *pointer() { if ( !singleton::is_valid() ) { new T(); } return singleton::pointer(); } static T &reference() { if ( !singleton::is_valid() ) { new T(); } return singleton::reference(); } }; } // namespace nv #endif // NV_SINGLETON_HH