LCOV - code coverage report
Current view: top level - core - typefactory.h (source / functions) Coverage Total Hit
Test: coverage.info Lines: 100.0 % 12 12
Test Date: 2026-10-20 13:34:58 Functions: 100.0 % 27 27
Branches: 50.0 % 8 4

             Branch data     Line data    Source code
       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                 :             : 
      12                 :             : /**
      13                 :             :  * @brief Registry-based factory for creating objects by runtime identifier.
      14                 :             :  *
      15                 :             :  * Allows registering derived types and instantiating them using a ClassId key.
      16                 :             :  *
      17                 :             :  * Notes:
      18                 :             :  * - Not thread-safe. Register types during initialization phase only.
      19                 :             :  * - Re-registering the same id overwrites the previous entry ("last wins").
      20                 :             :  * - ClassId must be hashable (std::hash<ClassId> specialization must exist).
      21                 :             :  *
      22                 :             :  * @tparam ClassId Unique class identifier type (e.g. std::string, int, enum).
      23                 :             :  * @tparam BaseClass Base type for all created objects.
      24                 :             :  * @tparam Args Constructor arguments forwarded to registered derived types (by value).
      25                 :             :  *
      26                 :             :  * Usage example:
      27                 :             :  * @code
      28                 :             :  * #include <string>
      29                 :             :  *
      30                 :             :  * struct Base {
      31                 :             :  *   virtual ~Base() = default;
      32                 :             :  *   virtual int get() = 0;
      33                 :             :  * };
      34                 :             :  *
      35                 :             :  * struct Derived1 : Base {
      36                 :             :  *   explicit Derived1(int start) : m_start(start) {}
      37                 :             :  *   int get() override { return m_start + 1; }
      38                 :             :  *   int m_start = 0;
      39                 :             :  * };
      40                 :             :  *
      41                 :             :  * struct Derived2 : Base {
      42                 :             :  *   explicit Derived2(int start) : m_start(start) {}
      43                 :             :  *   int get() override { return m_start + 2; }
      44                 :             :  *   int m_start = 0;
      45                 :             :  * };
      46                 :             :  *
      47                 :             :  * TypeFactory<std::string, Base, int> factory;
      48                 :             :  * factory.registerType<Derived1>("one");
      49                 :             :  * factory.registerType<Derived2>("two");
      50                 :             :  *
      51                 :             :  * std::shared_ptr<Base> a = factory.create("one", 10);
      52                 :             :  * std::shared_ptr<Base> b = factory.creator("two")(10); // advanced API: get creator function
      53                 :             :  *
      54                 :             :  * (void)a->get();
      55                 :             :  * (void)b->get();
      56                 :             :  * @endcode
      57                 :             :  */
      58                 :             : template<class ClassId, class BaseClass, class... Args>
      59                 :             : class TypeFactory {
      60                 :             : public:
      61                 :             :     /** @brief Shared ownership handle returned for created instances. */
      62                 :             :     using BasePtr = std::shared_ptr<BaseClass>;
      63                 :             :     /** @brief Registered creator function signature. */
      64                 :             :     using CreatorFn = BasePtr (*)(Args...);
      65                 :             : 
      66                 :         950 :     TypeFactory() = default;
      67                 :             : 
      68                 :             :     /**
      69                 :             :      * @brief Registers a Derived type under the given id.
      70                 :             :      *
      71                 :             :      * Requirements (checked at compile-time):
      72                 :             :      * - Derived must inherit from BaseClass
      73                 :             :      * - Derived must be constructible from Args...
      74                 :             :      *
      75                 :             :      * Re-registering the same id overwrites the previous entry ("last wins").
      76                 :             :      */
      77                 :             :     template<class Derived>
      78                 :       14238 :     void registerType(const ClassId &id) {
      79                 :             :         static_assert(std::is_base_of_v<BaseClass, Derived>,
      80                 :             :                       "Derived must inherit from BaseClass");
      81                 :             :         static_assert(std::is_constructible_v<Derived, Args...>,
      82                 :             :                       "Derived must be constructible from Args...");
      83                 :             : 
      84         [ +  - ]:       14238 :         classes.insert_or_assign(id, &instantiate<Derived>);
      85                 :       14238 :     }
      86                 :             : 
      87                 :             :     /**
      88                 :             :      * @brief Returns creator function for the given id.
      89                 :             :      * @throws std::out_of_range when id is not registered.
      90                 :             :      */
      91                 :       14241 :     [[nodiscard]] CreatorFn creator(const ClassId &id) const {
      92                 :       14241 :         return classes.at(id);
      93                 :             :     }
      94                 :             : 
      95                 :             :     /**
      96                 :             :      * @brief Creates an instance for the given id using provided arguments.
      97                 :             :      * @throws std::out_of_range when id is not registered.
      98                 :             :      */
      99                 :       14239 :     [[nodiscard]] BasePtr create(const ClassId &id, Args... args) const {
     100         [ +  - ]:       14239 :         return creator(id)(std::move(args)...);
     101                 :             :     }
     102                 :             : 
     103                 :             :     /**
     104                 :             :      * @brief Checks whether an id is registered.
     105                 :             :      */
     106                 :           2 :     [[nodiscard]] bool contains(const ClassId &id) const {
     107         [ +  - ]:           2 :         return classes.find(id) != classes.end();
     108                 :             :     }
     109                 :             : 
     110                 :             : protected:
     111                 :             :     /** @brief Registered creators; accessible to derived factories. */
     112                 :             :     std::unordered_map<ClassId, CreatorFn> classes;
     113                 :             : 
     114                 :             : private:
     115                 :             :     template<class Derived>
     116                 :       14240 :     static BasePtr instantiate(Args... args) {
     117         [ +  - ]:       14240 :         return std::make_shared<Derived>(std::move(args)...);
     118                 :             :     }
     119                 :             : };
     120                 :             : #endif// TYPEFACTORY_H
        

Generated by: LCOV version 2.0-1