3

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

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

示例(请耐心等待,我不太确定你能做到这一点)。

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

char functions [3] = ["hello()","run()","find()"];

当我读取配置文件并显示运行 hello() 时,我可以使用数组运行它吗(我可以找到数组中是否存在测试)

我也可以轻松地将新函数添加到数组中。

注意:我知道它不能用数组来完成,所以只是一个例子

4

4 回答 4

5

我想是这样的。

#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

于 2012-07-18T06:06:25.097 回答
4

从您的 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);

这意味着每次您使用这种语句添加新的源文件时,它都会自动添加到您可以执行的函数列表中。

于 2012-07-18T06:18:30.960 回答
3

使用指向函数的指针来完成它。

例如(我不确定语法):

map<string,void(*)()> funcs;

然后做funcs[name]();

于 2012-07-18T06:05:16.350 回答
1

查看函数指针(也称为“函子”)。您可以有条件地调用对您选择的各种函数之一的引用,而不是调用特定函数。此处的教程提供了对该主题的详细介绍。

于 2012-07-18T06:13:51.273 回答