IQRF Gateway Daemon
ObjectFactory.h
Go to the documentation of this file.
1 /*
2  * Copyright 2016-2017 MICRORISC s.r.o.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #pragma once
18 
19 #include "PlatformDep.h"
20 #include "IqrfLogging.h"
21 #include <map>
22 #include <functional>
23 #include <memory>
24 
32 template<typename T, typename R>
34 {
35 private:
37  typedef std::function<std::unique_ptr<T>(R&)> CreateObjectFunc;
39  std::map<std::string, CreateObjectFunc> m_creators;
40 
48  template<typename S>
49  static std::unique_ptr<T> createObject(R& representation) {
50  return std::unique_ptr<T>(ant_new S(representation));
51  }
52 public:
59  template<typename S>
60  void registerClass(const std::string& id){
61  if (m_creators.find(id) != m_creators.end()){
62  THROW_EX(std::logic_error, "Duplicit registration of: " << PAR(id));
63  }
64  m_creators.insert(std::make_pair(id, createObject<S>));
65  }
66 
72  bool hasClass(const std::string& id){
73  return m_creators.find(id) != m_creators.end();
74  }
75 
83  std::unique_ptr<T> createObject(const std::string& id, R& representation){
84  auto iter = m_creators.find(id);
85  if (iter == m_creators.end()){
86  THROW_EX(std::logic_error, "Unregistered creator for: " << PAR(id));
87  }
88  //calls the required createObject() function
89  return std::move(iter->second(representation));
90  }
91 };
std::unique_ptr< T > createObject(const std::string &id, R &representation)
Create object based on data representation.
Definition: ObjectFactory.h:83
void registerClass(const std::string &id)
Template function to register object creator function.
Definition: ObjectFactory.h:60
Create object based on data representation.
Definition: ObjectFactory.h:33
bool hasClass(const std::string &id)
Check if a creator object is registered.
Definition: ObjectFactory.h:72