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


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

相关推荐
asdfg12589633 分钟前
小程序开发中的JS和Go的对比及用途
开发语言·javascript·golang
FL16238631298 分钟前
基于yolo11实现的车辆实时交通流量进出统计与速度测量系统python源码+演示视频
开发语言·python·音视频
华如锦18 分钟前
四:从零搭建一个RAG
java·开发语言·人工智能·python·机器学习·spring cloud·计算机视觉
2501_9418752823 分钟前
在东京复杂分布式系统中构建统一可观测性平台的工程设计实践与演进经验总结
c++·算法·github
每天吃饭的羊32 分钟前
媒体查询
开发语言·前端·javascript
Jacen.L34 分钟前
SIGABRT (6) 中止信号详解
c++
北海有初拥40 分钟前
Python基础语法万字详解
java·开发语言·python
阿里嘎多学长1 小时前
2026-01-02 GitHub 热点项目精选
开发语言·程序员·github·代码托管
王老师青少年编程1 小时前
信奥赛C++提高组csp-s之并查集(案例实践)2
数据结构·c++·并查集·csp·信奥赛·csp-s·提高组
天远云服1 小时前
Go语言高并发实战:集成天远手机号码归属地核验API打造高性能风控中台
大数据·开发语言·后端·golang