Libftpp
A modern C++ library
singleton.hpp
Go to the documentation of this file.
1 #ifndef SINGLETON_HPP
2 #define SINGLETON_HPP
3 
4 #include <memory>
5 #include <stdexcept>
6 
36 template <typename TType>
37 class Singleton
38 {
39 private:
40  //
41  // Note : Utiliser inline pour éviter les erreurs de linkage
42  // quand ce header est inclus dans plusieurs fichiers .cpp
43  //
44  static inline std::unique_ptr<TType> _instance = nullptr;
45 
46 public:
47  static TType* instance()
48  {
49  if (!_instance)
50  throw std::runtime_error("Instance not yet created.");
51 
52  return _instance.get();
53  }
54 
55  template <typename... TArgs>
56  static void instantiate(TArgs... p_args)
57  {
58  if (_instance != nullptr)
59  throw std::runtime_error("Instance already exists.");
60 
61  _instance = std::make_unique<TType>((p_args)...);
62  }
63 
64  static void reset()
65  {
66  _instance = nullptr;
67  }
68 };
69 
70 #endif
Singleton Design Pattern.
Definition: singleton.hpp:38
static TType * instance()
Definition: singleton.hpp:47
static void reset()
Definition: singleton.hpp:64
static void instantiate(TArgs... p_args)
Definition: singleton.hpp:56