Storing Functions with Distinct Signatures in a Map
In C , creating a map with string keys and generic functions as values poses a challenge. However, utilizing a combination of type erasure and a templated operator(), this can be achieved.
Type erasure allows the storage of different function types in a single container, while the templated operator() provides access to the stored functions. The code example below demonstrates this approach:
#include <any> #include <functional> #include <map> #include <string> template<typename Ret> struct AnyCallable { template<typename ... Args> Ret operator()(Args&& ... args) { ... } std::any m_any; }; void foo(int x, int y) { ... } void bar(std::string x, int y, int z) { ... } int main() { std::map<std::string, AnyCallable<void>> map; map["foo"] = &foo; map["bar"] = &bar; map["foo"](1, 2); map["bar"]("Hello", 1, 2); }
In this solution, the AnyCallable class acts as a wrapper around the stored functions, providing the templated operator(). The function pointers &foo and &bar are converted to std::function objects before being stored in the m_any member. When the stored functions are invoked, they are cast to the appropriate function type and executed.
It's important to note that due to type erasure, matching arguments must be provided at the call site. Furthermore, the const-ness of function arguments is significant, as different overloads may be created with the same number of arguments but different qualifiers.
The above is the detailed content of How to Store Functions with Different Signatures in a Map in C ?. For more information, please follow other related articles on the PHP Chinese website!