【发布时间】:2023-03-17 11:31:02
【问题描述】:
问题用包含字符串作为键和函数指针作为值的映射替换我的 if 和 else 语句。但是,每个函数指针都可以指向具有不同返回类型和不同参数的函数,而无需使用 boost。基本上我想知道的是如何创建一个以通用函数指针为值的映射。
以下是我要解决的问题的简化版本。所需的输出。
#include<iostream>
int addtwoNumber(int a, int b){
return a+b;
}
bool isEqual(std::string str, int number){
return std::stoi(str)==number;
}
int main(){
// create a map that contains funtion pointers
template<typename ReturnType, typename... Args>
std::map<std::string, ReturnType (*)(Args...)> actionMap; // create a map<string, function pointer>
actionMap.insert(std::make_pair("one", &addtwoNumber)); // add functions to the map
actionMap.insert(std::make_pair("two", &isEqual));
std::cout << "type commands and arguments: " << std::endl;
std::string command;
std::cin >> command;
auto func = actionMap.find(command[0]);
std::cout << *func() << std::endl; // how do I pass the arguments to the function
}
期望的输出:
./test.out
one 2 5 /user input
7 /Output of the program
./test.out
two 5 5
true
【问题讨论】:
-
退后一步。你想在这里完成什么?
-
您尝试通过您需要帮助的解决方案解决的实际问题是什么?请read about the XY problem.
-
您展示的程序是您想要工作的实际程序吗?这不是简化,是另一个程序的MCVE?你没有另一个程序有一些你想通过使用函数指针映射来解决的问题吗?如果您确实有其他程序,并且您显示的程序不是实际程序,请告诉我们实际程序中的实际问题,因为您要求我们帮助您解决问题而不告诉我们您实际上要解决什么问题。请阅读我之前评论中的链接。
-
std::cout
-
此外,了解您遇到的实际错误总是有帮助的,因此请编辑您的问题以包括您收到的实际(完整、完整和未经编辑的)错误,包括任何信息注释和消息.
标签: c++ function-pointers variadic-templates stdmap