以字符串为参数的C++调用函数

标签 c++ maps

假设我有几个函数,例如 function1()function2()、.....、function1000() 我在一个函数中得到一个字符串让我们说 call_function(string function_name)
现在我需要执行基于 function_name 的函数。

我搜索了解决方案,发现我可以使用 map 。

有什么简单的方法可以为 1000 个 keys(string type) 和相应的函数创建映射?
例如:call_function(function541) 然后它应该执行 function541();

最佳答案

你可以使用 map 来为这些东西提供函数指针

void func1(const char *args)
{
     //....
}

void func2(const char *args)
{
     //....
}

typedef void (*function) (const char *args);

//......

std::map<std::string, function> func_map;

func_map.insert(std::pair<std::string, function>("func1", func1));
func_map.insert(std::pair<std::string, function>("func2", func2));

func_map["func1"]("arg1 arg2 arg3"); // Here is the func1 call

关于以字符串为参数的C++调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40437588/

相关文章:

c++ - 为什么 Visual Studio 无法在模板类中选择正确的构造函数?

c++ - 在 Code::Blocks on linux 中为 C++ GUI appz 设置 gtkmm-3.0

python - 在 map 投影后不连续时修复形状多边形对象

objective-c - 使用 WebView 从 Google map 获取 Cocoa/Objective-C 回调

java - 不可变集和映射上的 JDK9 随机化

google-maps - 将 Google map 嵌入到网站中

c++ - 将 map 数据的 vector 复制到 vector 图中

c++ - 初始化 asio::ip::address_v6() 的最快方法?

c++ - 防止编码器在物理模拟中出现错误 "forget to divide by time"

c++ - EOS CDT : where are the *. h 和文件系统中存储的 *.cpp 文件,我需要引用它们来编译