AsyncFw 1.2
Async Framework is c++ runtime with timers, poll notifiers, sockets, coroutines, etc.
 
Loading...
Searching...
No Matches
Instance.h
1/*
2Copyright (c) 2026 Alexandr Kuzmuk
3
4This file is part of the AsyncFw project. Licensed under the MIT License.
5See {Link: LICENSE file https://mit-license.org} in the project root for full license information.
6*/
7
8#pragma once
9
10#include <vector>
11#include <string>
12
13namespace AsyncFw {
16public:
17 class List : public std::vector<AbstractInstance *> {
18 friend AbstractInstance;
19
20 public:
21 static void destroyValues();
22
23 void append(AbstractInstance *);
24 void remove(AbstractInstance *);
25
26 private:
27 ~List();
28 };
29
30protected:
31 static class List list;
32
33 virtual ~AbstractInstance() = default;
34 virtual void destroyValue() = 0;
35 std::string name;
36};
37
39template <typename T>
40class Instance : public AbstractInstance {
41 friend T;
42
43public:
44 template <typename CT, typename... Args>
45 static CT *create(Args... args) {
46 if (!i_->value) {
47 CT *_v = new CT(args...);
48 if (!i_->value) {
49 i_->value = _v;
50 i_->created();
51 }
52 return static_cast<CT *>(i_->value);
53 }
54 return nullptr;
55 }
56 template <typename... Args>
57 static T *create(Args... args) {
58 return create<T>(args...);
59 }
60 static void set(T *p) { i_->value = p; }
61 static T *get() { return i_->value; }
62
63 Instance(const std::string &_name = {}) : value(nullptr) {
64 name = _name;
65 list.append(i_ = this);
66 }
67 virtual ~Instance() override {
68 Instance<T>::destroyValue();
69 list.remove(i_);
70 }
71
72protected:
73 Instance(const Instance &) = delete;
74 void destroyValue() override {
75 if (value) delete value;
76 }
77 virtual void created() {}
78
79private:
80 T *value;
81 inline static Instance<T> *i_;
82};
83} // namespace AsyncFw
The AbstractInstance class.
Definition Instance.h:15