VSM C++ SDK
Vehicle Specific Modules SDK
singleton.h
Go to the documentation of this file.
1 // Copyright (c) 2014, Smart Projects Holdings Ltd
2 // All rights reserved.
3 // See LICENSE file for license details.
4 
11 #ifndef SINGLETON_H_
12 #define SINGLETON_H_
13 
14 #include <memory>
15 #include <mutex>
16 
17 namespace ugcs {
18 namespace vsm {
19 
20 namespace internal {
21 
25 template <class T, class = void>
27 public:
31  static std::shared_ptr<T>
33  {
34  return nullptr;
35  }
36 
42  template <typename... Args>
43  static std::shared_ptr<T>
44  Create(Args &&...args)
45  {
46  return std::make_shared<T>(std::forward<Args>(args)...);
47  }
48 };
49 
51 template <class T>
52 class Singleton_creator<T, typename std::enable_if<std::is_default_constructible<T>::value>::type> {
53 public:
55  template <typename... Args>
56  static std::shared_ptr<T>
57  Create(Args &&...args)
58  {
59  return std::make_shared<T>(std::forward<Args>(args)...);
60  }
61 };
62 
63 } /* namespace internal */
64 
68 template <class T>
69 class Singleton {
70 public:
72  Singleton(const Singleton &) = delete;
73 
74  Singleton() = default;
75 
85  template <typename... Args>
86  std::shared_ptr<T>
87  Get_instance(Args &&...args)
88  {
89  auto ptr = instance.lock();
90  if (!ptr) {
91  ptr = internal::Singleton_creator<T>::Create(std::forward<Args>(args)...);
92  instance = ptr;
93  }
94  return ptr;
95  }
96 
97 private:
99  std::weak_ptr<T> instance;
100 };
101 
102 } /* namespace vsm */
103 } /* namespace ugcs */
104 
105 #endif /* SINGLETON_H_ */
UGCS root namespace.
Definition: android-linux/ugcs/vsm/platform_sockets.h:27
STL namespace.
static std::shared_ptr< T > Create(Args &&...args)
Always can create an instance.
Definition: singleton.h:57
static std::shared_ptr< T > Create(Args &&...args)
Create singleton instance.
Definition: singleton.h:44
std::shared_ptr< T > Get_instance(Args &&...args)
Get singleton instance.
Definition: singleton.h:87
Helper class for singletons instantiation.
Definition: singleton.h:26
static std::shared_ptr< T > Create()
Get singleton instance for a class which does not have default constructor.
Definition: singleton.h:32
Helper class for implementing singletons.
Definition: singleton.h:69