Using simple interest has never been so easy and hassle-free, support two-segment construction, direct sticker code
#ifndef _singleton_h_#define _singleton_h_#include "Simple_ptr.h" #include <functional> #if defined (_enable_ multithread) #include <mutex> #endifnamespace Purelib {namespace GC {///CLASS TEMPLATE Singleton, support delay I NIT with variadic args Template<typename _ty> class Singleton {Public:template<typename ... _ args> static _ty* instance (_args...args) {if (nullptr = = Singleton<_ty>::__single__.get ()) {#if defined (_enable_multithread) singleton<_ty>::__mutex__.lock (); #endif if (nullptr = = Singleton<_ty>::__single__.get ()) {singleton<_ty>::__sing Le__.reset (new _ty); Delay_init (args ...); } #if defined (_enable_multithread) singleton<_ty>::__mutex__.unlock (); #endif} r Eturn Singleton<_ty>::__single__.get (); } static void DestroY (void) {if (Singleton<_ty>::__single__.get ()! = nullptr) {SINGLETON&L T;_ty>::__single__.reset (); }} private:template<typename _fty, TypeName ... args> static void Delay_init (const _fty& MEMF, Args...args) {//init use specific member Func with M Ore than 1 args std::mem_fn (memf) (Singleton<_ty>::__single__.get (), args ...); } template<typename _fty, typename arg> static void Delay_init (const _fty& memf, const arg& AR g) {//init use specific member Func with 1 arg std::mem_fun (MEMF) (singleton<_ty>::__single__.get (), Arg); } template<typename _fty> static void Delay_init (const _fty& MEMF) {//init use specific M Ember func no args Std::mem_fun (memf) (Singleton<_ty>::__single__.get ()); } static void Delay_init (void) {//No Init } private:static simple_ptr<_ty> __single__; #if defined (_enable_multithread) static Std::mutex __mutex__; #endif}; Template<typename _ty> simple_ptr<_ty> singleton<_ty>::__single__; #if defined (_ENABLE_ multithread) template<typename _ty> Std::mutex singleton<_ty>::__mutex__; #endif};}; #endif/** Copyright (c) 2012-2014 by X.D. Guo All rights reserved.* Consult your license regarding permissions and Restri Ctions. v3.0:2011 * *
C++11 Singleton class template implementation