代码之家  ›  专栏  ›  技术社区  ›  a a

在一个数组中存储不同的函数指针?

  •  0
  • a a  · 技术社区  · 3 年前

    如果我有两个这样的函数:

    void funcA(std::string str);
    
    void funcB(int32_t i, int32_t j);
    

    我可以在同一个映射中存储指向这两个函数的指针吗?例子:

    std::unordered_map<std::string, SomeType> map;
    map.emplace("funcA", &funcA);
    map.emplace("funcB", &funcB);
    map["funcA"]("test");
    map["funcB"](3,4);
    

    有工作吗?或者是某种带有std::函数的模板。

    编辑: 函数也可以有不同的返回类型。 附言: 我目前正在学习视频游戏中的回调和事件管理器。

    0 回复  |  直到 3 年前
        1
  •  1
  •   Yakup Beyoglu    3 年前

    很抱歉被误解了,你可以在下面找到解决方案。

    #include <iostream>
    #include <map>
    
    typedef void (*customfunction)();
    
    void hello() {
        std::cout<<"hello" << std::endl;
    }
    
    void hello_key(std::string value){
            std::cout<<"hello " << value << std::endl;
    }
    
    void hello_key_2(int value){
            std::cout<<"hello " << value << std::endl;
    }
    
    int main(){
        
    
        std::map<std::string, customfunction> function_map;
        
        function_map.emplace("test",customfunction(&hello));
        function_map.emplace("test-2",customfunction(&hello_key));
        function_map.emplace("test-3",customfunction(&hello_key_2));
    
        function_map["test"]();
        ((void(*)(std::string))function_map["test-2"])("yakup");
        ((void(*)(int))function_map["test-3"])(4);
        
        return 0;
    }
    
        2
  •  -1
  •   passing_through    3 年前

    你的函数有不同的类型,但是 map 需要一个 value_type .你可以用 std::tuple 类型为“键”,函数指针为“值”:

    void funcA(std::string) {}
    void funcB(int32_t, int32_t) {}
    
    int main() {
        std::tuple map{funcA, funcB};
        get<decltype(&funcA)>(map)("abc");
        get<decltype(&funcB)>(map)(1, 2);
    }