Created
March 31, 2020 09:37
-
-
Save avasyukov/2f25156fd9cb54fb7b7979b8515765da to your computer and use it in GitHub Desktop.
C++ dispatch table sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <functional> | |
#include <unordered_map> | |
#include <algorithm> | |
using namespace std; | |
// Какие-то функции, которые мы хотим вызывать. | |
// Состав параметров и тип возвращаемых значений совпадает. | |
void foo(int a){ | |
cout << "Foo: " << a << endl; | |
} | |
void bar(int z) { | |
cout << "Bar: " << z << endl; | |
} | |
int main() { | |
// Таблица вызова: | |
// - тип ключа - строка | |
// - тип значения - void-овая функция, которая принимает параметром int | |
unordered_map<std::string, std::function<void(int)> > dispatchTable; | |
// Пара значений в таблице | |
dispatchTable["foo"] = foo; | |
dispatchTable["bar"] = bar; | |
// Считаем, что хотим вызвать | |
string action; | |
cin >> action; | |
// Если такой ключ есть в таблице, ... | |
if(dispatchTable.find(action) != dispatchTable.end()) { | |
// ... то вызываем найденную функцию (с параметром 42, прибитым гвоздями в коде), ... | |
dispatchTable[action](42); | |
} else { | |
// ... а если ключа такого нет, то пишем, что вызвать нам нечего. | |
cout << "Unknown action: " << action << endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment