YARP
Yet Another Robot Platform
Dispatcher.h
Go to the documentation of this file.
1 /*
2  * SPDX-FileCopyrightText: 2006-2021 Istituto Italiano di Tecnologia (IIT)
3  * SPDX-FileCopyrightText: 2006-2010 RobotCub Consortium
4  * SPDX-License-Identifier: BSD-3-Clause
5  */
6 
7 #ifndef YARP_OS_IMPL_DISPATCHER_H
8 #define YARP_OS_IMPL_DISPATCHER_H
9 
11 
12 #include <cstdio>
13 #include <map>
14 #include <string>
15 #include <vector>
16 
18 
19 namespace yarp {
20 namespace os {
21 namespace impl {
22 
26 template <class T, class RET>
28 {
29 private:
30  class Entry
31  {
32  public:
33  std::string name;
34  RET (T::*fn)(int argc, char* argv[]);
35 
36  Entry(const char* name, RET (T::*fn)(int argc, char* argv[])) :
37  name(name),
38  fn(fn)
39  {
40  }
41 
42  Entry() :
43  fn(nullptr)
44  {
45  }
46  };
47 
48  std::map<std::string, Entry> action;
49  std::vector<std::string> names;
50 
51 public:
52  void add(const char* name, RET (T::*fn)(int argc, char* argv[]))
53  {
54  Entry e(name, fn);
55  action[std::string(name)] = e;
56  // maintain a record of order of keys
57  names.push_back(std::string(name));
58  }
59 
60  RET dispatch(T* owner, const char* name, int argc, char* argv[])
61  {
62  std::string sname(name);
63  typename std::map<std::string, Entry>::const_iterator it = action.find(sname);
64  if (it != action.end()) {
65  return (owner->*(it->second.fn))(argc, argv);
66  } else {
67  yCError(DISPATCHER, "Could not find command \"%s\"", name);
68  }
69  return RET();
70  }
71 
72  std::vector<std::string> getNames()
73  {
74  return names;
75  }
76 };
77 
78 } // namespace impl
79 } // namespace os
80 } // namespace yarp
81 
82 
83 #endif // YARP_OS_IMPL_DISPATCHER_H
const yarp::os::LogComponent & DISPATCHER()
Definition: Dispatcher.cpp:9
Dispatch to named methods based on string input.
Definition: Dispatcher.h:28
std::vector< std::string > getNames()
Definition: Dispatcher.h:72
void add(const char *name, RET(T::*fn)(int argc, char *argv[]))
Definition: Dispatcher.h:52
RET dispatch(T *owner, const char *name, int argc, char *argv[])
Definition: Dispatcher.h:60
#define yCError(component,...)
Definition: LogComponent.h:154
#define YARP_DECLARE_LOG_COMPONENT(name)
Definition: LogComponent.h:74
The main, catch-all namespace for YARP.
Definition: dirs.h:16