fork download
  1. #include <iostream>
  2. #include <map>
  3. #include <functional>
  4. using namespace std;
  5.  
  6. enum MessageType { MSG_NONE = -1, MSG_TYPE_START_PROCESS, MSG_TYPE_END_PROCESS };
  7.  
  8. typedef std::map<MessageType, std::function<void()>> MessageFuncMap;
  9.  
  10. void startProcess()
  11. {
  12. cout << "start process" << endl;
  13. }
  14.  
  15. void endProcess()
  16. {
  17. cout << "end process" << endl;
  18. }
  19.  
  20. void defaultOutput(MessageType msgType)
  21. {
  22. cout << "unknown message type: " << (int)msgType << endl;
  23. }
  24.  
  25. void callFunc(MessageFuncMap msgFunc, MessageType msgType, std::function<void(MessageType)> defaultFunc = nullptr)
  26. {
  27. auto it = msgFunc.find(msgType);
  28. if (it != msgFunc.end())
  29. (it->second)();
  30. else
  31. if (defaultFunc != nullptr)
  32. defaultFunc(msgType);
  33. }
  34.  
  35. void callMessageFunc(MessageFuncMap msgFunc, MessageType msgType)
  36. {
  37. callFunc(msgFunc, msgType, defaultOutput);
  38. }
  39.  
  40. int main() {
  41. MessageFuncMap msgFunc;
  42.  
  43. msgFunc[MSG_TYPE_START_PROCESS] = startProcess;
  44. msgFunc[MSG_TYPE_END_PROCESS] = endProcess;
  45.  
  46. callMessageFunc(msgFunc, MSG_TYPE_START_PROCESS);
  47. callMessageFunc(msgFunc, MSG_TYPE_END_PROCESS);
  48. callMessageFunc(msgFunc, MSG_NONE);
  49.  
  50. return 0;
  51. }
  52.  
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
start process
end process
unknown message type: -1