switcher是切换状态用的,接受一个输入,返回加下来该转到哪个状态
func是该状态要执行的内容
#include <iostream>
#include <functional>
#include <string>
#include <vector>
#include <map>
struct State
{
std::function<std::string(char)> switcher;
std::function<void()> func;
};
struct FSM
{
std::map<std::string, State> states;
State *curr;
bool running;
// 注册一个状态
void reg(const std::string &name, const State &state)
{
states.insert(std::pair<std::string, State>{name, state});
}
// 处理输入
void process(char ch)
{
std::string result = curr->switcher(ch);
if (result.empty())
{
running = false;
return;
}
curr = &states.at(result);
curr->func();
}
};
std::string start_switcher(char ch)
{
if (ch == '6')
return "end";
else
return "start";
}
std::string end_switcher(char) { return ""; }
void start_func()
{
std::cout << "start" << std::endl;
}
void end_func()
{
std::cout << "end" << std::endl;
}
int main(int argc, char *argv[])
{
State start;
start.switcher = start_switcher;
start.func = start_func;
State end;
end.switcher = end_switcher;
end.func = end_func;
FSM fsm;
fsm.reg("start", start);
fsm.reg("end", end);
// 设置初始状态
fsm.running = true;
fsm.curr = &start;
// 运行
fsm.curr->func();
while (fsm.running)
{
char ch;
std::cin>>ch;
fsm.process(ch);
}
return 0;
}