le2d v0.4.7
2D game engine framework
 
Loading...
Searching...
No Matches
service_locator.hpp
Go to the documentation of this file.
1#pragma once
2#include <klib/assert.hpp>
3#include <gsl/pointers>
4#include <typeindex>
5#include <unordered_map>
6
7namespace le {
9 public:
10 template <typename Type>
11 void bind(Type* service) {
12 KLIB_ASSERT(service != nullptr);
13 m_services.insert_or_assign(typeid(Type), service);
14 }
15
16 template <typename Type>
17 void unbind() {
18 m_services.erase(typeid(Type));
19 }
20
21 template <typename Type>
22 [[nodiscard]] auto contains() const -> bool {
23 return find<Type>() != nullptr;
24 }
25
26 template <typename Type>
27 [[nodiscard]] auto find() const -> Type* {
28 auto const it = m_services.find(typeid(Type));
29 if (it == m_services.end()) { return nullptr; }
30 return static_cast<Type*>(it->second.get());
31 }
32
33 template <typename Type>
34 [[nodiscard]] auto get() const -> Type& {
35 KLIB_ASSERT(contains<Type>());
36 return *find<Type>();
37 }
38
39 [[nodiscard]] auto service_count() const -> std::size_t { return m_services.size(); }
40 void clear() { m_services.clear(); }
41
42 private:
43 std::unordered_map<std::type_index, gsl::not_null<void*>> m_services{};
44};
45} // namespace le
Definition service_locator.hpp:8
void bind(Type *service)
Definition service_locator.hpp:11
auto get() const -> Type &
Definition service_locator.hpp:34
void unbind()
Definition service_locator.hpp:17
auto service_count() const -> std::size_t
Definition service_locator.hpp:39
void clear()
Definition service_locator.hpp:40
auto contains() const -> bool
Definition service_locator.hpp:22
auto find() const -> Type *
Definition service_locator.hpp:27
Definition animation.hpp:8