Vanetza
 
Loading...
Searching...
No Matches
factory.hpp
1#ifndef FACTORY_HPP_QLKNHPWZ
2#define FACTORY_HPP_QLKNHPWZ
3
4#include <functional>
5#include <map>
6#include <memory>
7#include <utility>
8
9namespace vanetza
10{
11
12/**
13 * Factory for a group of classes implementing T
14 */
15template<typename T, typename... Args>
17{
18public:
19 using Result = std::unique_ptr<T>;
20 using Function = std::function<Result(Args...)>;
21
22 Factory() : m_default(m_functions.end())
23 {
24 }
25
26 /**
27 * Create an instance of T using a named implementation
28 * \param name of wanted implementation
29 * \return created instance or nullptr if not found
30 */
31 Result create(const std::string& name, Args... args) const
32 {
33 std::unique_ptr<T> obj;
34 auto found = m_functions.find(name);
35 if (found != m_functions.end()) {
36 obj = found->second(std::forward<Args>(args)...);
37 }
38 return obj;
39 }
40
41 /**
42 * Create object using default implementation
43 * \return created instance or nullptr if no default is configured
44 */
45 Result create(Args... args) const
46 {
47 std::unique_ptr<T> obj;
48 if (m_default != m_functions.end()) {
49 obj = m_default->second(std::forward<Args>(args)...);
50 }
51 return obj;
52 }
53
54 /**
55 * Add an implementation to factory
56 * \param name of implementation
57 * \param f function creating a new instance of this implementation
58 * \return true if added successfully, i.e. no previous addition with same name
59 */
60 bool add(const std::string& name, Function f)
61 {
62 return m_functions.emplace(name, std::move(f)).second;
63 }
64
65 /**
66 * Set default implementation
67 * \param name selected default implementation
68 * \return true if an implementation exists with selected name
69 */
70 bool configure_default(const std::string& name)
71 {
72 m_default = m_functions.find(name);
73 return m_default != m_functions.end();
74 }
75
76private:
77 using map_type = std::map<std::string, Function>;
78 map_type m_functions;
79 typename map_type::const_iterator m_default;
80};
81
82} // namespace vanetza
83
84#endif /* FACTORY_HPP_QLKNHPWZ */
85
Result create(const std::string &name, Args... args) const
Definition: factory.hpp:31
bool configure_default(const std::string &name)
Definition: factory.hpp:70
bool add(const std::string &name, Function f)
Definition: factory.hpp:60
Result create(Args... args) const
Definition: factory.hpp:45