In my current setup, I have a
typedef std::function<void (MyClass&, std::vector<std::string>) MyFunction;
std::map<std::string, MyFunction> dispatch_map;
And I register my functions in it with a macro. However, I have a problem with this: the parameters are passed as a vector of strings, which I have to convert inside the functions. I would rather do this conversion outside the functions, at the dispatcher level. Is this possible? The function signatures are known at compile time, and never change at run time.
You can get pretty far with variadic templates and some template/virtual techniques. With the following codes, you’ll be able to do something like:
output:
Full implementation:
These codes are exemplary. You should optimize it to provide perfect forwarding less redundancy in parameter list expansion.
Headers and a test-function
This helps us parsing a string and putting results into a tuple:
This unfolds a function pointer and a tuple into a function call (by function-pointer):
This function puts it together:
Here’s our test:
Warning: Code needs more verification upon parsing and should use
std::function<>instead of naked function pointerBased on above code, it is simple to write a function-registry:
One could even think of supporting function overloading with this, using a multimap and dispatching decisions based on what content is on the passed arguments.
Here’s how to use it: