C++ 有限元状态机

测试
cpp 复制代码
#include <iostream>
#include "state_machine.h"

class Context {
public:
    char input;
};

class TurnOn : public sm::Event<Context> {
public:
    bool triggered() {
        if(context->input=='1') {
            std::cout << "switch on" << std::endl;
            return true;
        }

        return false;
    }
};

class TurnOff : public sm::Event<Context> {
public:
    bool triggered() {
        if(context->input=='2') {
            std::cout << "switch off" << std::endl;
            return true;
        }

        return false;
    }
};

class On : public sm::State<Context> {
    void enter() {
        std::cout << "enter On state" << std::endl;
    }

    void execute() {
        std::cout << "execute On state" << std::endl;
    }

    void exit() {
        std::cout << "exit On state" << std::endl;
    }
};

class Off : public sm::State<Context> {
    void enter() {
        std::cout << "enter Off state" << std::endl;
    }

    void execute() {
        std::cout << "execute Off state" << std::endl;
    }

    void exit() {
        std::cout << "exit Off state" << std::endl;
    }
};

int main() {

    TurnOn turn_on;
    TurnOff turn_off;
    On on;
    Off off;

    Context context;
    sm::StateMachine<2, 2, Context> sm(&on, &context);

    sm.transit(&on, &off, &turn_off);
    sm.transit(&off, &on, &turn_on);
    sm.start();

    while(true) {
        std::cin >> context.input;

        sm.update();
    }
}
效果

enter On state

1

execute On state

2

switch off

exit On state

enter Off state

execute Off state

3

execute Off state

1

switch on

exit Off state

enter On state

execute On state

0

参考

https://github.com/Eryk-Mozdzen/state-machine-cpp


创作不易,小小的支持一下吧!

相关推荐
源代码•宸13 分钟前
前置准备:定时微服务背景和现状
开发语言·经验分享·后端·微服务·云原生·架构·golang
2601_9673387114 分钟前
C#上位机开发零基础入门到精通全套视频
开发语言·c#
雪的季节43 分钟前
Multisim14.0的详细中文安装步骤【附安装包】
c++
小白学大数据1 小时前
超简单:用 Python 让 Excel 飞起来:用 openpyxl 把重复报表整理交给脚本
开发语言·数据库·python·excel
旧梦95271 小时前
Java SortedMap 接口详解:从入门到实战
java·开发语言
莫陌尛.1 小时前
Java_this构造方法
java·开发语言
Persistent的粽子!2 小时前
C++:类与对象(二)
开发语言·c++
Dreams°1232 小时前
【Java后端+Vue前后端分离:内网正常、公网访问异常|5个高频经典踩坑完整复盘】
java·开发语言·vue.js
蒸蒸yyyyzwd2 小时前
cpp 选手备战秋招学习笔记 day23
c++·求职招聘
.YM.Z2 小时前
C++ STL 容器深度剖析:vector 与 list 的模拟实现及对比
开发语言·c++·vector·list