1 #pragma once 2 3 #include <mutex> 4 #include <memory> 5 6 template <typename Type> class CSingleton 7 { 8 public: GetInstance()9 static Type& GetInstance() 10 { 11 std::call_once(m_onceFlag, 12 [] () 13 { 14 m_instance.reset(new Type()); 15 } 16 ); 17 return *m_instance; 18 } 19 20 private: 21 static std::unique_ptr<Type> m_instance; 22 static std::once_flag m_onceFlag; 23 }; 24 25 template <typename Type, typename DependantType> class CDependantSingleton 26 { 27 public: GetInstance()28 static Type& GetInstance() 29 { 30 std::call_once(m_onceFlag, 31 [] () 32 { 33 m_instance.reset(new Type(DependantType::GetInstance())); 34 } 35 ); 36 return *m_instance; 37 } 38 39 private: 40 static std::unique_ptr<Type> m_instance; 41 static std::once_flag m_onceFlag; 42 }; 43 44 template <typename Type> std::unique_ptr<Type> CSingleton<Type>::m_instance; 45 template <typename Type> std::once_flag CSingleton<Type>::m_onceFlag; 46 47 template <typename Type, typename DependantType> std::unique_ptr<Type> CDependantSingleton<Type, DependantType>::m_instance; 48 template <typename Type, typename DependantType> std::once_flag CDependantSingleton<Type, DependantType>::m_onceFlag; 49