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


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

相关推荐
NG WING YIN16 分钟前
Golang關於信件的
开发语言·深度学习·golang
Sunny_yiyi21 分钟前
Java根据模版导出PDF文件
java·开发语言·pdf
橘子1325 分钟前
C++实战:搜索引擎项目(二)
开发语言·c++·搜索引擎
赵谨言1 小时前
基于python人物头像的卡通化算法设计与实现
开发语言·经验分享·python
应用市场1 小时前
Qt C++ 图形绘制完全指南:从基础到进阶实战
开发语言·c++·qt
楼田莉子1 小时前
python小项目——学生管理系统
开发语言·python·学习
yuanpan1 小时前
使用Python创建本地Http服务实现与外部系统数据对接
开发语言·python·http
青草地溪水旁1 小时前
设计模式(C++)详解—单例模式(2)
c++·单例模式
bkspiderx1 小时前
C++时区操作全版本指南(含C++03/C++11-17/C++20)
linux·开发语言·c++·c++20·时区
ljf88382 小时前
Java导出复杂excel,自定义excel导出
java·开发语言·excel