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

后端 未结 5 1569
抹茶落季
抹茶落季 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:21

    The thing is, somehow, when you call your functions, you already know what type they will be.

    If we do something like

    int x = map["key"](1, "2")
    

    we can already deduce that whatever function is stored in "key" is of type (int (*)(int, char*)) so we might as well have done something like

    int x = map_of_int_and_string_to_int["key"](1, "2");
    

    and avoid all the hassle of merging all the keys together... While it is true that C++ has some overloading features precisely for this kind of stuff I can't really see why you should bother in this particular case.

    And in the end, why would you want to put all those functions in the same map in the first place? They don't share any similar interfaces so you can't uniformly access them, you can't iterate over them and you can't opaquely pass them around to someone else. Without anything in common there is nothing you can safely do to the functions in this hypothetical map.

提交回复
热议问题