Storing Functions with Varied Signatures in a Map
In C , you may encounter the need to store functions with varying signatures in a map, where the key is a string and the value is a generic method. While this may initially seem challenging, it's possible with the help of type erasure and a template operator.
Type Erasure
To enable storing functions with different signatures in a map, we first type-erase them into a container. This involves converting the function types into a common representation that can be stored and retrieved from the map.
Template Operator
Once the function types have been type-erased, we provide a template operator () for the map. This operator takes the stored function as input and allows us to call it with specific parameters at runtime. The parameters provided must match the original function signature exactly. If they don't, the operator will throw a std::bad_any_cast exception.
Example
Here's an example of how this can be implemented:
#include <any> #include <functional> #include <map> #include <string> #include <iostream> template<typename Ret> struct AnyCallable { //... }; void foo(int x, int y) { //... } void bar(std::string x, int y, int z) { //... } using namespace std::literals; int main() { // Initialize the map std::map<std::string, AnyCallable<void>> map; // Store functions in the map map["foo"] = &foo; map["bar"] = &bar; // Call the stored functions with parameters map["foo"](1, 2); map["bar"]("Hello, std::string literal"s, 1, 2); }
In this example, we define a wrapper struct AnyCallable that type-erases functions and provides a template operator () for calling them.
Considerations
The above is the detailed content of How can I store functions with varying signatures in a map in C ?. For more information, please follow other related articles on the PHP Chinese website!