在C/C++中自动调用函数
Calling functions automatically in C/C++
我的主程序读取配置文件,配置文件告诉它要运行哪些函数。函数在一个单独的文件中,目前,当我创建一个新函数时,我必须在主程序中添加函数调用(因此,当配置文件指示时,它可以被调用)
我的问题是,有没有什么方法可以让主程序单独运行,当我添加一个新函数时,可以通过某种数组调用它。
例如(请原谅,我不太确定你能不能做到这一点)。
我有一个数组(或枚举),
char functions [3] = ["hello()","run()","find()"];
当我读取配置文件,它说运行hello()时,我可以使用数组运行它吗(我可以找到数组中是否存在测试)
我还可以很容易地向数组添加新函数。
注意:我知道这不能用数组来完成,所以只是一个例子
我想是这样的。
#include <functional>
#include <map>
#include <iostream>
#include <string>
void hello()
{
std::cout << "Hello" << std::endl;
}
void what()
{
std::cout << "What" << std::endl;
}
int main()
{
std::map<std::string, std::function<void()>> functions =
{
std::make_pair("hello", hello),
std::make_pair("what", what)
};
functions["hello"]();
}
http://liveworkspace.org/code/49685630531cd6284de6eed9b10e0870
从main中暴露一个函数,该函数可以在映射中注册新的元组{ function_name, function_pointer}
(如其他答案所建议的)。
通常:
// main.h
typedef void (*my_function)(void *);
int register_function(const std::string &name, my_function function);
// main.c
int register_function(const std::string &name, my_function function)
{
static std::map<std::string, my_function> s_functions;
s_functions[name] = function;
return 0;
}
int main()
{
for( std::map<std::string, my_function>::const_iterator i=s_functions.begin();
i != s_functions.end();
++i)
{
if( i->second )
{
// excecute each function that was registered
(my_function)(i->second)(NULL);
}
}
// another possibility: execute only the one you know the name of:
std::string function_name = "hello";
std::map<std::string, my_function>::const_iterator found = s_functions.find(function_name);
if( found != s_functions.end() )
{
// found the function we have to run, do it
(my_function)(found->second)(NULL);
}
}
现在,在每个实现要运行的函数的auther源文件中,执行以下操作:
// hello.c
#include "main.h"
void my_hello_function(void *)
{
// your code
}
static int s_hello = register_function("hello", &my_hello);
这意味着,每次添加带有此类语句的新源文件时,它都会自动添加到可执行的函数列表中。
使用指向函数的指针来执行此操作。
例如(我不确定语法):
map<string,void(*)()> funcs;
然后进行funcs[name]();
检查函数指针(也称为"functors")。您可以有条件地调用对所选各种函数之一的引用,而不是调用特定函数。这里的教程提供了对该主题的详细介绍。
相关文章:
- 如何用参数值调用函数(仅在运行时已知)
- 从python中调用C++函数并获取返回值
- 当使用通配符和null指针调用函数时,对输出的说明
- 从R调用C++函数并对其进行集成时出错
- 使用QTreeView,如何通过调用函数只突出显示特定的行/列
- 如何在qt中从另一个类调用函数
- 在 COUT 语句中使用 COUT 调用函数
- 如何从线程中的不同模块调用函数?
- C++从函数指针数组调用函数
- 当 A 在 for 循环中调用函数 B 时,如何计算函数 A 的空间复杂度?
- 如何在 C/C++ 中从外部库调用函数
- 如何使用运算符在同一行中多次调用函数
- 是否可以创建一个从不同类调用函数的线程?
- 无法为类成员调用函数
- 如何从另一个标头 c++ 调用函数
- C++有什么方法可以在既不调用函数模板也不提供其模板参数的情况下引用函数模板?
- 如何只允许在调用函数 B 后调用函数 A?
- 我可以这样调用函数吗?
- 如何在 c++ 的类中递归调用函数方法?
- 为什么在指向对象的迭代器上调用函数不允许我更改对象本身?