You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

114 lines
2.3KB

  1. #include <cassert>
  2. #include <iostream>
  3. template <class K, class ... A>
  4. void FiniteStateMachine<K, A...>::registerStateCreator(K const& key, StateCreator&& creator)
  5. {
  6. m_creators.emplace(key, std::move(creator));
  7. std::cout << "Registered state: " << std::to_string(key) << std::endl;
  8. }
  9. template <class K, class ... A>
  10. template <class State>
  11. void FiniteStateMachine<K, A...>::registerStateType(K const& key)
  12. {
  13. auto creator = [](A&& ... args)
  14. {
  15. return std::unique_ptr<AState>{new State{std::forward<A>(args)...}};
  16. };
  17. registerStateCreator(key, std::move(creator));
  18. }
  19. template <class K, class ... A>
  20. auto FiniteStateMachine<K, A...>::currentState()const -> AState&
  21. {
  22. assert( !m_stack.empty() );
  23. return *(m_stack.top().state);
  24. }
  25. template <class K, class ... A>
  26. K const& FiniteStateMachine<K, A...>::currentStateKey()const
  27. {
  28. assert( !m_stack.empty() );
  29. return m_stack.top().key;
  30. }
  31. template <class K, class ... A>
  32. bool FiniteStateMachine<K, A...>::hasState()const
  33. {
  34. return !m_stack.empty();
  35. }
  36. template <class K, class ... A>
  37. void FiniteStateMachine<K, A...>::push(K const& key, A&& ... args)
  38. {
  39. auto arguments = std::make_tuple(std::forward<A>(args)...);
  40. pushEvent([&, key]()
  41. {
  42. pushImp(key, std::forward<A>(args)...);
  43. });
  44. }
  45. template <class K, class ... A>
  46. void FiniteStateMachine<K, A...>::change(K const& key, A&& ... args)
  47. {
  48. pushEvent([&, key]()
  49. {
  50. changeImp(key, std::forward<A>(args)...);
  51. });
  52. }
  53. template <class K, class ... A>
  54. void FiniteStateMachine<K, A...>::pop()
  55. {
  56. pushEvent([this]()
  57. {
  58. popImp();
  59. });
  60. }
  61. template <class K, class ... A>
  62. void FiniteStateMachine<K, A...>::clear()
  63. {
  64. pushEvent([this]()
  65. {
  66. clearImp();
  67. });
  68. }
  69. template <class K, class ... A>
  70. auto FiniteStateMachine<K, A...>::createState(K const& key, A&& ... args) -> StatePointer
  71. {
  72. auto creatorIt = m_creators.find(key);
  73. assert( creatorIt != m_creators.end() );
  74. return creatorIt->second(std::forward<A>(args)...);
  75. }
  76. template <class K, class ... A>
  77. void FiniteStateMachine<K, A...>::processEvents()
  78. {
  79. while (!m_eventQueue.empty())
  80. {
  81. m_eventQueue.front()();
  82. m_eventQueue.pop();
  83. }
  84. }
  85. template <class K, class ... A>
  86. void FiniteStateMachine<K, A...>::pushEvent(Event&& event)
  87. {
  88. m_eventQueue.emplace(std::move(event));
  89. }
  90. template <class K, class ... A>
  91. void FiniteStateMachine<K, A...>::step()
  92. {
  93. processEvents();
  94. }