DBC Framework
DBC parsing and CAN signal decoding framework
Loading...
Searching...
No Matches
typefactory.h
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2026 Dim Himro
3
4#ifndef TYPEFACTORY_H
5#define TYPEFACTORY_H
6
7#include <memory>
8#include <type_traits>
9#include <unordered_map>
10#include <utility>// std::move
11
58template<class ClassId, class BaseClass, class... Args>
60public:
61 using BasePtr = std::shared_ptr<BaseClass>;
62 using CreatorFn = BasePtr (*)(Args...);
63
64 TypeFactory() = default;
65
75 template<class Derived>
76 void registerType(const ClassId &id) {
77 static_assert(std::is_base_of_v<BaseClass, Derived>,
78 "Derived must inherit from BaseClass");
79 static_assert(std::is_constructible_v<Derived, Args...>,
80 "Derived must be constructible from Args...");
81
82 classes.insert_or_assign(id, &instantiate<Derived>);
83 }
84
89 [[nodiscard]] CreatorFn creator(const ClassId &id) const {
90 return classes.at(id);
91 }
92
97 [[nodiscard]] BasePtr create(const ClassId &id, Args... args) const {
98 return creator(id)(std::move(args)...);
99 }
100
104 [[nodiscard]] bool contains(const ClassId &id) const {
105 return classes.find(id) != classes.end();
106 }
107
108protected:
109 // Protected by design: derived factories may extend/inspect the registry.
110 std::unordered_map<ClassId, CreatorFn> classes;
111
112private:
113 template<class Derived>
114 static BasePtr instantiate(Args... args) {
115 return std::make_shared<Derived>(std::move(args)...);
116 }
117};
118#endif// TYPEFACTORY_H
Registry-based factory for creating objects by runtime identifier.
Definition typefactory.h:59
bool contains(const ClassId &id) const
Checks whether an id is registered.
BasePtr create(const ClassId &id, Args... args) const
Creates an instance for the given id using provided arguments.
Definition typefactory.h:97
void registerType(const ClassId &id)
Registers a Derived type under the given id.
Definition typefactory.h:76
CreatorFn creator(const ClassId &id) const
Returns creator function for the given id.
Definition typefactory.h:89