Loading [MathJax]/extensions/TeX/AMSmath.js
Radium Engine  1.5.0
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Modules Pages
Singleton.hpp
1 #pragma once
2 
3 #include <Core/RaCore.hpp>
4 
5 #include <memory>
6 
7 // Singleton utility.
8 // This file give you two macros to automatically implement a class
9 // as a singleton.
10 // I used to be a template like you, then I took a DLL to the knee...
11 
12 // Usage : The singleton instance is initially set to null.
13 // To create the instance, call `createInstance( )` with the
14 // class constructor arguments.
15 // To access the singleton instance, call getInstance().
16 // The singleton instance can also be destroyed (reset to null).
17 
21 #define RA_SINGLETON_INTERFACE( TYPE ) \
22  protected: \
23  TYPE( const TYPE& ) = delete; \
24  void operator=( const TYPE& ) = delete; \
25  struct Deleter { \
26  void operator()( TYPE* p ) const { delete p; } \
27  }; \
28  static std::unique_ptr<TYPE, Deleter> s_instance; \
29  \
30  public: \
31  template <typename... Args> \
32  inline static TYPE* createInstance( const Args&... args ) { \
33  s_instance = std::unique_ptr<TYPE, Deleter>( new TYPE( args... ), Deleter() ); \
34  return getInstance(); \
35  } \
36  inline static TYPE* getInstance() { return s_instance.get(); } \
37  inline static void destroyInstance() { s_instance.reset( nullptr ); }
38 
40 // Limitations : TYPE cannot be a nested type
41 // RA_SINGLETON_IMPLEMENTATION(A::MySingleton); will *not* work.
42 #define RA_SINGLETON_IMPLEMENTATION( TYPE ) \
43  std::unique_ptr<TYPE, TYPE::Deleter> TYPE::s_instance = nullptr; \
44  class TYPE
45 // The line above is just there to make the macro end with a ;