ORCA: Optimization-based framework for Robotic Control Applications
Factory.h
Go to the documentation of this file.
1 #pragma once
2 
3 #include <memory>
4 #include <map>
5 #include <functional>
6 #include <orca/utils/Utils.h>
8 
9 namespace orca
10 {
11  namespace common
12  {
13  class Factory
14  {
15  public:
16  static Factory* Instance()
17  {
18  static Factory factory;
19  return &factory;
20  }
21  std::shared_ptr<ConfigurableOrcaObject> createPtr(const std::string& instance_name,const std::string& class_name)
22  {
23  if(instance_name.empty())
24  {
25  std::cout << "[Factory] Instance name is empty !" << '\n';
26  return nullptr;
27  }
28 
29  if(!utils::key_exists(m_,class_name))
30  {
31  std::cout << "[Factory] Class name '" << class_name << "' is not present in the factory." << '\n';
33  std::cout << "[Factory] Did you forget to add ORCA_REGISTER_CLASS(" << class_name << ") at the end to the class cpp file ?" << '\n';
34  return nullptr;
35  }
36  auto c = m_[class_name](instance_name);
37  if(!c)
38  {
40  return nullptr;
41  }
42  std::cout << "[Factory] '" << instance_name << "' of type " << class_name << " successfully created" << '\n';
43  return c;
44  }
45  bool registerClass(const std::string& class_name,std::function<std::shared_ptr<ConfigurableOrcaObject>(const std::string&)> f)
46  {
47  if(utils::key_exists(m_,class_name))
48  return false;
49  std::cout << "[Factory] " << "Successfully registered class " << class_name << '\n';
50  m_[class_name] = f;
51  return true;
52  }
54  {
55  if(m_.empty())
56  {
57  std::cout << "[Factory] Factory is empty !" << '\n';
58  return;
59  }
60  std::cout << "[Factory] Available classes : " << '\n';
61  for(auto c : m_)
62  {
63  std::cout << " - " << c.first << '\n';
64  }
65  }
66  private:
67  std::map<std::string,std::function<std::shared_ptr<ConfigurableOrcaObject>(const std::string&)> > m_;
68  };
69 
70  } // namespace common
71 } // namespace orca
72 
73 
74 #define ORCA_REGISTER_CLASS(CLASSNAME,...) \
75 namespace { \
76  bool ok##__VA_ARGS__ = ::orca::common::Factory::Instance()->registerClass(#CLASSNAME,[](const std::string& name) { return std::make_shared<CLASSNAME>(name); }); \
77 };
bool registerClass(const std::string &class_name, std::function< std::shared_ptr< ConfigurableOrcaObject >(const std::string &)> f)
Definition: Factory.h:45
Definition: Factory.h:13
void printAvailableClasses()
Definition: Factory.h:53
std::shared_ptr< ConfigurableOrcaObject > createPtr(const std::string &instance_name, const std::string &class_name)
Definition: Factory.h:21
static Factory * Instance()
Definition: Factory.h:16
bool key_exists(const std::map< Key, Vals > &container, const Key &key)
Definition: Utils.h:249
Definition: CartesianAccelerationPID.h:44