如果我有兩個這樣的功能:
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::any 會起作用嗎?或者可能是某種帶有 std::function 的模板。
編輯:函式也可以有不同的回傳型別。PS:我目前正在學習電子游戲中的回呼和事件管理器。
uj5u.com熱心網友回復:
抱歉誤解了,您可以在下面找到解決方案。
#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;
}
uj5u.com熱心網友回復:
您的函式有不同的型別,但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);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/347769.html
