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