How to store functional objects with different signatures in a container?

后端 未结 5 1558
抹茶落季
抹茶落季 2020-11-27 23:40

So imagine we had 2 functions (void : ( void ) ) and (std::string : (int, std::string)) and we could have 10 more. All (or some of them) take in di

5条回答
  •  温柔的废话
    2020-11-28 00:14

    You can do it by casting function pointers to void pointers and back. You're expected to know the signature during run-time, so it wouldn't be an issue to hard-wire the casting operators. However the logic of doing it escapes me. It doesn't make sense at all, at least in C++. Using template classes/functions or structs of function pointers makes much more sense.

    for example, with templates:

    template  foo(X param1) { /* do something with param1*/};
    template  foo(X param1, Y param2)
       {/* do something with 2 params*/};
    template  foo(X param1) { /* only one parameter, which is int */};
    

    now:

    foo(5); // calls the third one
    foo("5"); // calls the first one
    foo("5", 5); // calls the second one.
    

    Who needs a map?

提交回复
热议问题