Radium Engine  1.5.20
Loading...
Searching...
No Matches
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 { \
27 delete p; \
28 } \
29 }; \
30 static std::unique_ptr<TYPE, Deleter> s_instance; \
31 \
32 public: \
33 template <typename... Args> \
34 inline static TYPE* createInstance( const Args&... args ) { \
35 s_instance = std::unique_ptr<TYPE, Deleter>( new TYPE( args... ), Deleter() ); \
36 return getInstance(); \
37 } \
38 inline static TYPE* getInstance() { \
39 return s_instance.get(); \
40 } \
41 inline static void destroyInstance() { \
42 s_instance.reset( nullptr ); \
43 }
44
46// Limitations : TYPE cannot be a nested type
47// RA_SINGLETON_IMPLEMENTATION(A::MySingleton); will *not* work.
48#define RA_SINGLETON_IMPLEMENTATION( TYPE ) \
49 std::unique_ptr<TYPE, TYPE::Deleter> TYPE::s_instance = nullptr; \
50 class TYPE
51// The line above is just there to make the macro end with a ;