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


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

相关推荐
reasonsummer14 小时前
【办公类-115-06】20250920职称资料上传04——docx复制、docx转PDF(课程表11个)
开发语言·windows·python·c#
栀寒老醑15 小时前
Python实现的服务器日志监控脚本
开发语言·python
星星点点洲15 小时前
PostgreSQL 15二进制文件
开发语言·设计模式·golang
小糖学代码15 小时前
Linux:11.线程概念与控制
linux·服务器·c语言·开发语言·c++
yaoxin52112316 小时前
211. Java 异常 - Java 异常机制总结
java·开发语言·python
Larry_Yanan18 小时前
QML学习笔记(四十)QML的ApplicationWindow和StackView
c++·笔记·qt·学习·ui
Empty_77718 小时前
编程之python基础
开发语言·python
疯狂吧小飞牛19 小时前
Lua 中的 __index、__newindex、rawget 与 rawset 介绍
开发语言·junit·lua
Kratzdisteln21 小时前
【C语言】Dev-C++如何编译C语言程序?从安装到运行一步到位
c语言·c++
寻星探路21 小时前
Java EE初阶启程记13---JUC(java.util.concurrent) 的常见类
java·开发语言·java-ee