In C , the need arises to associate functions with different signatures with unique identifiers for dynamic invocation based on runtime arguments. However, the standard containers do not directly support the storage of non-homogenous function types.
One approach to overcome this limitation is type erasure, which involves encapsulating function types into a container that erases specific type information. This allows for the uniform storage of functions with varying signatures. To facilitate this process, a custom data structure, AnyCallable, is defined:
template<typename Ret> struct AnyCallable { AnyCallable() {} template<typename F> AnyCallable(F&& fun) : AnyCallable(std::function(std::forward<F>(fun))) {} template<typename ... Args> AnyCallable(std::function<Ret(Args...)> fun) : m_any(fun) {} template<typename ... Args> Ret operator()(Args&& ... args) { return std::invoke(std::any_cast<std::function<Ret(Args...)>>(m_any), std::forward<Args>(args)...); } std::any m_any; };
The AnyCallable accepts heterogeneous function types and provides a generic operator() for invoking the encapsulated function with matching arguments.
Using the AnyCallable data structure, we can now create a map that stores functions with different signatures:
std::map<std::string, AnyCallable<void>> map; map["foo"] = &foo; map["bar"] = &bar;
To invoke the functions dynamically based on their unique string identifiers, we utilize the operator() provided by AnyCallable:
map["foo"](1, 2); map["bar"]("Hello", 1, 2);
This approach ensures type safety and dynamic invocation of functions with non-homogenous signatures, making it a versatile solution for storing and executing method pointers with different inputs.
The above is the detailed content of How Can You Store Functions with Non-Homogeneous Signatures in a Map in C ?. For more information, please follow other related articles on the PHP Chinese website!