Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Singleton.h
- #ifdef _MSC_VER
- # if defined(_M_X64) || defined(_M_AMD64)
- # define BREAKPOINT() do {__asm {int 03h}} while(0)
- # else
- # pragma intrinsic(__debugbreak)
- # define BREAKPOINT() __debugbreak()
- # endif
- #endif
- template <class T>
- class CSingleton
- {
- public:
- inline CSingleton()
- {
- if(ms_bInstanceCreated)
- BREAKPOINT();
- ms_pInstance = ((T *)this);
- ms_bInstanceCreated = true;
- }
- inline ~CSingleton()
- {
- ms_pInstance = nullptr;
- ms_bInstanceCreated = false;
- }
- private:
- static T * ms_pInstance;
- static bool ms_bInstanceCreated;
- };
- template <class T> T * CSingleton<T>::ms_pInstance = nullptr;
- template <class T> bool CSingleton<T>::ms_bInstanceCreated = false;
- // YourLib.h
- class CAppException
- {
- public:
- inline CAppException(const char *pError)
- {
- if(pError)
- std::strncpy(m_szError, pError, MAX_ERROR_LENGTH);
- else
- std::strcpy(m_szError, "<???>");
- }
- inline ~CAppException() = default;
- inline const char * GetError() const
- {
- return m_szError;
- }
- private:
- CAppException() = delete;
- enum { MAX_ERROR_LENGTH = 2048 };
- char m_szError[MAX_ERROR_LENGTH];
- };
- class CApp : public CSingleton<CApp>
- {
- public:
- ~CApp() = default;
- virtual void OnInit() {}
- virtual void OnRelease() {}
- virtual void OnFrame() = 0;
- virtual void OnError(CAppException &rEx) = 0;
- inline void Quit(int nCode)
- {
- m_bQuitting = true;
- m_nQuitCode = nCode;
- }
- protected:
- static int Run();
- private:
- CApp();
- bool m_bRunning;
- bool m_bQuitting;
- int m_nQuitCode;
- };
- // YourLib.cpp
- CApp::CApp() : m_bQuitting(false), m_nQuitCode(0)
- {}
- int CApp::Run()
- {
- if(m_bRunning)
- return 0;
- m_bRunning = true;
- try
- {
- OnInit();
- m_bQuitting = false;
- if(!m_bQuitting)
- OnFrame();
- }
- catch(CAppException &rEx)
- {
- OnError(rEx);
- }
- OnRelease();
- m_bRunning = false;
- return m_nQuitCode;
- }
- int main()
- {
- CApp *pApp = CApp::GetInstance();
- if(pApp)
- return pApp->Run();
- else
- return 0;
- }
- // ProgrammersCode.cpp
- class CProgrammersApp : public CApp
- {
- public:
- CProgrammersApp();
- ~CProgrammersApp();
- virtual void OnFrame() override;
- virtual void OnError(CAppException &rEx) override;
- };
- static CProgrammersApp s_ProgrammersApp;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement