Stochastic Loading Module
function_dispatcher.h
1 #ifndef _FUNCTION_DISPATCHER_H_
2 #define _FUNCTION_DISPATCHER_H_
3 
4 #include <functional>
5 #include <map>
6 #include <string>
7 #include <utility>
8 #include <vector>
9 
15 template <typename Treturntype, typename... Targs>
16 class Dispatcher {
17  public:
21  static Dispatcher* instance() {
22  static Dispatcher dispatcher;
23  return &dispatcher;
24  }
25 
31  void register_function(const std::string& key, std::function<Treturntype(Targs...)> new_function) {
32  if (!this->check(key)) {
33  registry[key] = std::move(new_function);
34  } else {
35  throw std::runtime_error("Duplicate key: " + key +
36  ", already registered. Verify key choice to "
37  "ensure function has not already been added");
38  }
39  }
40 
47  Treturntype dispatch(const std::string& key, Targs... args) {
48  if (!this->check(key)) {
49  throw std::runtime_error("Invalid key: " + key + ", not found in the function dispatcher");
50  } else {
51  return registry.at(key)(std::forward<Targs>(args)...);
52  }
53  }
54 
60  bool check(const std::string& key) const {
61  bool status = false;
62  for (const auto& keyvalue : registry)
63  if (keyvalue.first == key) status = true;
64  return status;
65  }
66 
71  std::vector<std::string> list() const {
72  std::vector<std::string> dispatcher_items;
73  for (const auto& keyvalue : registry)
74  dispatcher_items.push_back(keyvalue.first);
75  return dispatcher_items;
76  }
77 
78  private:
82  Dispatcher() = default;
83 
84  std::map<std::string, std::function<Treturntype(Targs...)>> registry;
87 };
88 
94 template <typename Treturntype, typename... Targs>
96  public:
102  const std::string& key,
103  std::function<Treturntype(Targs...)> new_function) {
104  // register the class factory function
106  key, std::move(new_function));
107  }
108 };
109 
110 #endif // _FUNCTION_DISPATCHER_H_
void register_function(const std::string &key, std::function< Treturntype(Targs...)> new_function)
Treturntype dispatch(const std::string &key, Targs...args)
static Dispatcher * instance()
DispatchRegister(const std::string &key, std::function< Treturntype(Targs...)> new_function)
bool check(const std::string &key) const
std::vector< std::string > list() const