SPARK  0.1.0
A general purpose game engine written in C++.
Loading...
Searching...
No Matches
Factory.h
1#pragma once
2
3#include "spark/patterns/details/Creators.h"
4
5#include "spark/base/Exception.h"
6
7#include <memory>
8
9namespace spark::patterns
10{
11 template <typename Key, typename BaseType, typename... Args>
12 template <typename TypeToRegister>
14 {
15 if (m_creators.contains(key))
16 throw spark::base::BadArgumentException("Type is already registered into the factory.");
17 m_creators[key] = std::make_unique<details::DerivedCreator<BaseType, TypeToRegister, Args...>>();
18 }
19
20 template <typename Key, typename BaseType, typename... Args>
21 typename Factory<Key, BaseType, Args...>::BasePtr Factory<Key, BaseType, Args...>::create(const Key& key, Args&&... args) const
22 {
23 if (!m_creators.contains(key))
24 throw spark::base::BadArgumentException("Type is not registered into the factory.");
25 return m_creators.at(key)->create(std::forward<Args>(args)...);
26 }
27
28 template <typename Key, typename BaseType, typename... Args>
29 typename Factory<Key, BaseType, Args...>::BasePtr Factory<Key, BaseType, Args...>::createOrFail(const Key& key, Args&&... args) const noexcept
30 {
31 if (!m_creators.contains(key))
32 return nullptr;
33 return m_creators.at(key)->create(std::forward<Args>(args)...);
34 }
35
36 template <typename Key, typename BaseType, typename... Args>
37 std::vector<Key> Factory<Key, BaseType, Args...>::registeredTypes() const noexcept
38 {
39 std::vector<Key> keys;
40 keys.reserve(m_creators.size());
41 for (const auto& [key, ptr] : m_creators)
42 keys.push_back(key);
43 return keys;
44 }
45}
Exception thrown when an argument is not valid.
Definition Exception.h:32
A factory class that creates objects of type BaseType.
Definition Factory.h:19
BasePtr createOrFail(const Key &key, Args &&... args) const noexcept
Creates an object of type BaseType.
Definition Factory.h:29
void registerType(const Key &key)
Registers a type the factory can create.
Definition Factory.h:13
std::vector< Key > registeredTypes() const noexcept
Gets a vector of all registered types in the factory.
Definition Factory.h:37
BasePtr create(const Key &key, Args &&... args) const
Creates an object of type BaseType. Throws an exception if the type is not registered.
Definition Factory.h:21
The creator for a derived class.
Definition Creators.h:31