EnTT  3.10.0
locator.hpp
1 #ifndef ENTT_LOCATOR_LOCATOR_HPP
2 #define ENTT_LOCATOR_LOCATOR_HPP
3 
4 #include <memory>
5 #include <utility>
6 #include "../config/config.h"
7 
8 namespace entt {
9 
26 template<typename Service>
27 struct locator final {
29  using type = Service;
30 
32  locator() = delete;
34  ~locator() = delete;
35 
40  [[nodiscard]] static bool has_value() ENTT_NOEXCEPT {
41  return (service != nullptr);
42  }
43 
53  [[nodiscard]] static Service &value() ENTT_NOEXCEPT {
54  ENTT_ASSERT(has_value(), "Service not available");
55  return *service;
56  }
57 
69  template<typename Impl = Service, typename... Args>
70  [[nodiscard]] static Service &value_or(Args &&...args) {
71  return service ? *service : emplace<Impl>(std::forward<Args>(args)...);
72  }
73 
81  template<typename Impl = Service, typename... Args>
82  static Service &emplace(Args &&...args) {
83  service = std::make_shared<Impl>(std::forward<Args>(args)...);
84  return *service;
85  }
86 
96  template<typename Impl = Service, typename Allocator, typename... Args>
97  static Service &allocate_emplace(Allocator alloc, Args &&...args) {
98  service = std::allocate_shared<Impl>(alloc, std::forward<Args>(args)...);
99  return *service;
100  }
101 
103  static void reset() ENTT_NOEXCEPT {
104  service.reset();
105  }
106 
107 private:
108  // std::shared_ptr because of its type erased allocator which is pretty useful here
109  inline static std::shared_ptr<Service> service = nullptr;
110 };
111 
112 } // namespace entt
113 
114 #endif
EnTT default namespace.
Definition: dense_map.hpp:22
Service locator, nothing more.
Definition: locator.hpp:27
static Service & value()
Returns a reference to a valid service, if any.
Definition: locator.hpp:53
static Service & value_or(Args &&...args)
Returns a service if available or sets it from a fallback type.
Definition: locator.hpp:70
static bool has_value()
Checks whether a service locator contains a value.
Definition: locator.hpp:40
static Service & allocate_emplace(Allocator alloc, Args &&...args)
Sets or replaces a service using a given allocator.
Definition: locator.hpp:97
~locator()=delete
Default destructor, deleted on purpose.
Service type
Service type.
Definition: locator.hpp:29
static Service & emplace(Args &&...args)
Sets or replaces a service.
Definition: locator.hpp:82
static void reset()
Resets a service.
Definition: locator.hpp:103
locator()=delete
Default constructor, deleted on purpose.