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 分钟前
基于 MATLAB 的插电混动汽车 CD-CS 策略 WLTC 前向仿真实现
开发语言·matlab·汽车
代钦塔拉10 分钟前
第一篇:工业级 C++/Qt 项目头文件包含原则:告别循环依赖与编译玄学
开发语言·c++·qt
谷雨不太卷26 分钟前
Linux基础IO
java·开发语言
神仙别闹1 小时前
基于PHP+MySQL实现在线考试系统
开发语言·mysql·php
fanzhonghong1 小时前
javaWeb开发之Maven高级
java·开发语言·spring boot·spring cloud·私服
luck_bor1 小时前
Lambda表达式 算法异常
java·开发语言
lsx2024061 小时前
SOAP Envelope 元素
开发语言
范范@1 小时前
day2-python基础语法
开发语言·python
qq_2518364571 小时前
基于java 私厨美食共享平台系统设计与实现(有源码)
java·开发语言·美食
ZPC82101 小时前
规划后的轨迹,如何发给 moveit_servo 执行
c++·人工智能·算法·3d