Gamedev Framework (gf)  0.12.0
A C++14 framework for 2D games
Singleton.h
1 /*
2  * Gamedev Framework (gf)
3  * Copyright (C) 2016-2019 Julien Bernard
4  *
5  * This software is provided 'as-is', without any express or implied
6  * warranty. In no event will the authors be held liable for any damages
7  * arising from the use of this software.
8  *
9  * Permission is granted to anyone to use this software for any purpose,
10  * including commercial applications, and to alter it and redistribute it
11  * freely, subject to the following restrictions:
12  *
13  * 1. The origin of this software must not be misrepresented; you must not
14  * claim that you wrote the original software. If you use this software
15  * in a product, an acknowledgment in the product documentation would be
16  * appreciated but is not required.
17  * 2. Altered source versions must be plainly marked as such, and must not be
18  * misrepresented as being the original software.
19  * 3. This notice may not be removed or altered from any source distribution.
20  */
21 #ifndef GF_SINGLETON_H
22 #define GF_SINGLETON_H
23 
24 #include <cassert>
25 #include <utility>
26 
27 #include "Portability.h"
28 
29 namespace gf {
30 #ifndef DOXYGEN_SHOULD_SKIP_THIS
31 inline namespace v1 {
32 #endif
33 
34  template<typename T>
36 
56  template<typename T>
57  class Singleton {
58  public:
66  : m_single(nullptr)
67  {
68  }
69 
73  Singleton(const Singleton&) = delete;
74 
78  Singleton(Singleton&&) = delete;
82  Singleton& operator=(const Singleton&) = delete;
83 
87  Singleton& operator=(Singleton&&) = delete;
88 
99  assert(m_single);
100  return *m_single;
101  }
102 
108  void reset() noexcept {
109  m_single = nullptr;
110  }
111 
117  bool isValid() const noexcept {
118  return m_single != nullptr;
119  }
120 
121  private:
122  friend class SingletonStorage<T>;
123 
124  T *m_single;
125  };
126 
149  template<typename T>
150  class SingletonStorage {
151  public:
159  template<typename ... Args>
160  SingletonStorage(Singleton<T>& ref, Args&&... args)
161  : m_storage(std::forward<Args>(args)...) {
162  assert(ref.m_single == nullptr);
163  ref.m_single = &m_storage;
164  }
165 
166  private:
167  T m_storage;
168  };
169 
170 #ifndef DOXYGEN_SHOULD_SKIP_THIS
171 }
172 #endif
173 }
174 
175 #endif // GF_SINGLETON_H
STL namespace.
void reset() noexcept
Reset the singleton.
Definition: Singleton.h:108
The namespace for gf classes.
Definition: Action.h:35
T & operator()()
Access the singleton.
Definition: Singleton.h:98
Singleton()
Default constructor.
Definition: Singleton.h:65
bool isValid() const noexcept
Check if the singleton has been initialized.
Definition: Singleton.h:117
SingletonStorage(Singleton< T > &ref, Args &&... args)
Construct a storage for a singleton.
Definition: Singleton.h:160
A storage for a singleton.
Definition: Singleton.h:35
A singleton that wraps a pointer provided by a storage.
Definition: Singleton.h:57