summaryrefslogtreecommitdiffstats
path: root/src/FSM.hpp
blob: 9570e266565b060b0e42ef41d1e13faa61c93fdb (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
#pragma once

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

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

	FSM(T &value) : state(value), previousState(value) {}

	~FSM() = default;

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

	void RegisterHandler(T state, std::function<void()> handler) {
		handlers[Transaction{state, state}] = handler;
	}

	void RegisterTransactionHandler(Transaction transaction, std::function<void()> handler) {
		handlers[transaction] = handler;
	}
};