fork download
  1. #include <iostream>
  2. #include <functional>
  3.  
  4. struct wrap
  5. {
  6. std::function<wrap ()> f;
  7. template<typename F>
  8. wrap(F f)
  9. : f(f)
  10. {
  11. }
  12. wrap operator()()
  13. {
  14. return f();
  15. }
  16. };
  17.  
  18. wrap menu_sub_1();
  19. wrap menu_sub_2();
  20. wrap menu_main()
  21. {
  22. std::cout
  23. << "Main menu" << std::endl
  24. << "1. Sub menu 1" << std::endl
  25. << "2. Sub menu 2" << std::endl
  26. << "3. Exit" << std::endl;
  27. int x;
  28. std::cin >> x;
  29. if(x == 1) return menu_sub_1;
  30. else if(x == 2) return menu_sub_2;
  31. else if(x == 3) std::exit(0);
  32. return menu_main;
  33. }
  34. wrap menu_sub_1()
  35. {
  36. std::cout
  37. << "Sub menu 1" << std::endl
  38. << "1. Back to main menu" << std::endl;
  39. int x;
  40. std::cin >> x;
  41. if(x == 1) return menu_main;
  42. return menu_sub_1;
  43. }
  44. wrap menu_sub_2()
  45. {
  46. std::cout
  47. << "Sub menu 2" << std::endl
  48. << "1. Back to main menu" << std::endl;
  49. int x;
  50. std::cin >> x;
  51. if(x == 1) return menu_main;
  52. return menu_sub_2;
  53. }
  54.  
  55. int main()
  56. {
  57. auto f = menu_main();
  58. while(true)
  59. {
  60. f = f();
  61. }
  62. }
  63.  
Success #stdin #stdout 0s 3464KB
stdin
1
1
2
1
3
stdout
Main menu
1. Sub menu 1
2. Sub menu 2
3. Exit
Sub menu 1
1. Back to main menu
Main menu
1. Sub menu 1
2. Sub menu 2
3. Exit
Sub menu 2
1. Back to main menu
Main menu
1. Sub menu 1
2. Sub menu 2
3. Exit