一个表驱动法的例子

#include <functional>
#include <iostream>
#include <unordered_map>
 
void (*fp1)() = []() {};
void (*fp2)() = []() { std::cout << "In fp2" << std::endl; };
void fp3() { std::cout << "In fp3" << std::endl; };
  
std::unordered_map<std::string, const std::function<void(void)>> table{
    {"1", fp1},
    {"2", fp2},
    {"3", fp3},
};
  
void calltable (const std::string& condition, std::unordered_map<std::string, const std::function<void(void)>>& table) {
  if (table.count(condition)) {
    table[condition]();
  }
}
  
int main(int argc, char *argv[]) {
  std::string condition = "1";
  calltable(condition, table);
  condition = "2";
  calltable(condition, table);
  condition = "3";
  calltable(condition, table);
}

  

posted @ 2023-11-29 11:48  南乡水  阅读(9)  评论(0编辑  收藏  举报