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


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

相关推荐
winfield821几秒前
MCP 协议详解
开发语言·网络·qt
cheems952742 分钟前
锁策略的介绍
java·开发语言
清水白石00843 分钟前
《Python × 数据库:用 SQLAlchemy 解锁高效 ORM 编程的艺术》
开发语言·python·json
风中月隐1 小时前
C语言中以坐标的方式图解“字母金字塔”的绘制
c语言·开发语言·算法·字母金子塔·坐标图解法
崇山峻岭之间1 小时前
C++ Prime Plus 学习笔记041
c++·笔记·学习
_风华ts1 小时前
虚函数与访问权限
c++
Arva .1 小时前
说说线程的生命周期和状态
java·开发语言
1001101_QIA1 小时前
C++中不能复制只能移动的类型
开发语言·c++
tryxr1 小时前
HashTable、HashMap、ConcurrentHashMap 之间的区别
java·开发语言·hash
serendipity_hky1 小时前
【go语言 | 第5篇】channel——多个goroutine之间通信
开发语言·后端·golang