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 小时前
22、双向链表作业实现与GDB调试实战
c语言·开发语言·网络·数据结构·链表·排序算法
xlq223227 小时前
22.多态(上)
开发语言·c++·算法
666HZ6667 小时前
C语言——高精度加法
c语言·开发语言·算法
星释8 小时前
Rust 练习册 100:音乐音阶生成器
开发语言·后端·rust
D_evil__8 小时前
[C++高频精进] 并发编程:线程基础
c++
风生u8 小时前
go进阶语法
开发语言·后端·golang
666HZ6668 小时前
C语言——黑店
c语言·开发语言
Gomiko8 小时前
JavaScript基础(八):函数
开发语言·javascript·ecmascript
〝七夜5699 小时前
JVM内存结构
java·开发语言·jvm
初级炼丹师(爱说实话版)9 小时前
JAVA泛型作用域与静态方法泛型使用笔记
java·开发语言·笔记