在C/C++中自动调用函数

Calling functions automatically in C/C++

本文关键字:调用 函数 C++      更新时间:2023-10-16

我的主程序读取配置文件,配置文件告诉它要运行哪些函数。函数在一个单独的文件中,目前,当我创建一个新函数时,我必须在主程序中添加函数调用(因此,当配置文件指示时,它可以被调用)

我的问题是,有没有什么方法可以让主程序单独运行,当我添加一个新函数时,可以通过某种数组调用它。

例如(请原谅,我不太确定你能不能做到这一点)。

我有一个数组(或枚举),

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")。您可以有条件地调用对所选各种函数之一的引用,而不是调用特定函数。这里的教程提供了对该主题的详细介绍。