1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#pragma once

#include <kooling/json/json.h>

#include <exception>

#include <plog/Log.h>

#include <functional>
#include <string>

namespace kooling::component {

template<typename I>
class factory
{
public:
    using pointer_type = std::unique_ptr<I>;
    using creator_type = std::function<pointer_type(const json_t&)>;
    using map_type     = std::unordered_map<std::string, creator_type>;

    static factory& instance()
    {
        static factory f;
        return f;
    }

    template<typename C>
    bool register_component()
    {
        std::string name{ C::name() };
        creator_type creator{ C::create };
        const auto ret{ d_map.try_emplace(std::move(name), std::move(creator)) };<--- Calling std::move(name)
        if (!ret.second)
        {
            PLOG_ERROR << "Sensor component already registered: \"" << name << "\"";<--- Access of moved variable 'name'.
        }
        return ret.second;
    }

    template<typename... Args>
    pointer_type create(const json_t& config, Args&&... args)
    {
        const std::string type{ config["type"] };
        if (const auto it{ d_map.find(type) }; it != d_map.end())
        {
            try
            {
                return it->second(config, std::forward<Args>(args)...);
            }
            catch (std::exception& e)
            {
                PLOG_ERROR
                    << "Could not build component \"" << type << "\": "
                    << e.what();
                return {};
            }
        }
        else
        {
            PLOG_ERROR << "Component \"" << type << "\" not found";
            return {};
        }
    }

private:
    factory()
    {}

    map_type d_map;
};

} // namespace kooling::component