Can I use a generic function type as the value of std::map? This eliminates the need to write different std::maps for different function parameters and return values.
template<class Function,class ... Args>
inline auto FuncWrapper(Function &&f, Args && ... args)-> decltype(f(std::forward<Args>(args)...))
{
return f(std::forward<Args>(args)...);
}
std::map<std::string, FuncWrapper>> FUNCS;
void test_map_operator()
{
FUNCS["MD5"]([](std::string data){ return "MD5: "+ data; }, "some data");
FUNCS["RSA"]([](std::string data, std::string key) {return "RSA: "+ data +':' + key;}, "some data", "some key");
FUNCS["Other"]([](int a, double b, char c){return (c-'0')+a+b;}, 1, 2.0, 'c');
}
A possibility could be to have a tagged union (but a known one) of closures (or function objects).
So combine std::function with std::variant and std::map.
For example, consider having some
std::map<std::string,
std::variant<std::function(void(int)>,
std::function(double(std::string))>> mapunion;
Your tagged union might contain smart pointers, e.g. some std::unique_ptr
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With