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 小时前
python画图|3D surface基础教程
开发语言·python
小于负无穷2 小时前
Go 中 Gin 框架的使用指南
开发语言·后端·golang·gin
周bro2 小时前
vue3使用panolens.js实现全景,带有上一个下一个,全屏功能
开发语言·javascript·ecmascript
白总Server3 小时前
rust解说
linux·开发语言·后端·golang·rust·debian·php
金庆3 小时前
Rust Pin
开发语言·后端·rust
Lill_bin3 小时前
CAS机制:并发编程中的原子操作
java·服务器·开发语言·windows·算法·微服务
wh233z3 小时前
Codeforces Round 969 (Div. 2) (A~D)
c语言·开发语言·数据结构·c++·算法·图论
曼亿点4 小时前
python的流程控制语句之制作空气质量评估系统
android·开发语言·python
奕星星奕4 小时前
QT QObject源码学习(二)
c++·qt
weixin_586062024 小时前
PHP 环境搭建教程
开发语言·php