Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put a generic function type into std::map? [duplicate]

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');
}
like image 451
s f Avatar asked Jul 26 '26 18:07

s f


1 Answers

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

like image 130
Basile Starynkevitch Avatar answered Jul 29 '26 10:07

Basile Starynkevitch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!