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


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

相关推荐
励志不掉头发的内向程序员1 小时前
STL库——string(类函数学习)
开发语言·c++
一百天成为python专家1 小时前
Python循环语句 从入门到精通
开发语言·人工智能·python·opencv·支持向量机·计算机视觉
Sunhen_Qiletian1 小时前
朝花夕拾(五)--------Python 中函数、库及接口的详解
开发语言·python
hqwest2 小时前
C#WPF实战出真汁07--【系统设置】--菜品类型设置
开发语言·c#·wpf·grid设计·stackpanel布局
前路不黑暗@2 小时前
C语言:操作符详解(二)
c语言·开发语言·经验分享·笔记·学习·学习方法·visual studio
深盾科技3 小时前
Kotlin Data Classes 快速上手
android·开发语言·kotlin
zzywxc7873 小时前
详细探讨AI在金融、医疗、教育和制造业四大领域的具体落地案例,并通过代码、流程图、Prompt示例和图表等方式展示这些应用的实际效果。
开发语言·javascript·人工智能·深度学习·金融·prompt·流程图
浮灯Foden3 小时前
算法-每日一题(DAY13)两数之和
开发语言·数据结构·c++·算法·leetcode·面试·散列表
淡海水3 小时前
【原理】Struct 和 Class 辨析
开发语言·c++·c#·struct·class
Q_Q19632884754 小时前
python的电影院座位管理可视化数据分析系统
开发语言·spring boot·python·django·flask·node.js·php