3

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');
}
s f
  • 107
  • 5
  • Interesting idea. I don’t believe there’s a way to do this directly because the types of the stored functions would be different. There may be some way to achieve this by adding a layer of indirection, though. – templatetypedef Jun 03 '20 at 04:17
  • You can do it, but it's a bad idea. – Caleth Jun 03 '20 at 08:11

2 Answers2

1

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

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
0

Using templates you cant achieve this.

Its a different type in C++.

Related to this would be the following: Take any stl container all of them provide a custom Allocater template, a big problem was that one container that had a different allocater wasnt assignable from the same container that had a different Allocater type.

Btw, because of this Bloomberg bd library rewrote stl containers just using virtual Allocaters which is ok because it uses dynamic dispatch.

Moshe Rabaev
  • 1,892
  • 16
  • 31
  • You must be coming from Java. There is no type erasure in C++. Templates are compile type concepts. Unless if you mean void*. – Moshe Rabaev Jun 03 '20 at 04:21
  • There is type erasure in C++, e.g. `std::function` erases the type of function objects – Caleth Jun 03 '20 at 08:12