summaryrefslogtreecommitdiffstats
path: root/src/FSM.hpp
blob: 346d0f00f446305946b7eeceb6fc7a475e68261e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#pragma once

#include <utility>
#include <functional>
#include <map>

template<class T>
class FSM {
public:
	using Transaction = std::pair<T, T>;
	using Handler = std::function<void(T &)>;

	FSM(T initialState) : state(initialState), previousState(initialState) {}

	~FSM() = default;

	void Update() {
		auto &handler = handlers[Transaction{previousState, state}];
		if (handler)
			handler(state);
		previousState = state;
	}

	void RegisterHandler(T state, Handler handler) {
		handlers[Transaction{state, state}] = handler;
	}

	void RegisterTransactionHandler(Transaction transaction, Handler handler) {
		handlers[transaction] = handler;
	}

private:
	T previousState;
	T state;
	std::map<Transaction, Handler> handlers;
};