簡體   English   中英

在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

使用函數指針可以做到這一點。

例如(我不確定語法):

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

然后執行funcs[name]();

從您的主對象公開一個可以在地圖中注冊新元組{ 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);
  }
}

現在,在實現了要運行的功能的每個身份驗證源文件中,執行以下操作:

// hello.c
#include "main.h"

void my_hello_function(void *)
{
  // your code
}

static int s_hello = register_function("hello", &my_hello);

這意味着,每次使用這種語句添加新的源文件時,該文件都會自動添加到您可以執行的功能列表中。

檢出函數指針 (也稱為“函數”)。 您可以有條件地調用對您選擇的各種功能之一的引用,而不必調用特定的函數。 此處的教程為該主題提供了詳細記錄的介紹。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM