1 #ifndef _FUNCTION_DISPATCHER_H_ 2 #define _FUNCTION_DISPATCHER_H_ 15 template <
typename Treturntype,
typename... Targs>
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);
35 throw std::runtime_error(
"Duplicate key: " + key +
36 ", already registered. Verify key choice to " 37 "ensure function has not already been added");
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");
51 return registry.at(key)(std::forward<Targs>(args)...);
60 bool check(
const std::string& key)
const {
62 for (
const auto& keyvalue : registry)
63 if (keyvalue.first == key) status =
true;
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;
84 std::map<std::string, std::function<Treturntype(Targs...)>> registry;
94 template <
typename Treturntype,
typename... Targs>
102 const std::string& key,
103 std::function<Treturntype(Targs...)> new_function) {
106 key, std::move(new_function));
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