一个表驱动法的例子

发布时间 2023-11-29 11:52:20作者: 南乡水
#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, void (*)()> table{
    {"1", fp1},
    {"2", fp2},
    {"3", fp3},
};

void calltable (const std::string& condition, std::unordered_map<std::string, void (*)()>& table) {
  for (const auto& [key, value] : table) {
    if (key == condition) {
      value();
      return;
    }
  }
}

int main(int argc, char *argv[]) {
  std::string condition = "1";
  calltable(condition, table);
  condition = "2";
  calltable(condition, table);
  condition = "3";
  calltable(condition, table);
}