Home > Blockchain >  Storing different function pointers in one array?
Storing different function pointers in one array?

Time:11-05

If I have two functions like this:

void funcA(std::string str);

void funcB(int32_t i, int32_t j);

Can I store pointers to both of these functions in the same map? Example:

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

Would std::any work? or maybe some kind of template with std::function.

Edit: Functions could also have different return types. PS: I am currently learning about Callbacks and Eventmanagers in videogames.

CodePudding user response:

sorry for misunderstood, you can find a solution below.

#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;
}

CodePudding user response:

Your functions have different types but map requires a single value_type. You can use std::tuple with types as "keys" and function pointers as "values":

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);
}
  • Related