Boost 提供了状态机的实现接口,采用了CRTP技术实现,下面以秒表为例子实现一个状态机,这是一个官方的例子,也可以参考资料:Boost Statechart 庫,状态机的状态转换图如下所示:
实现代码如下:
#include
#include
#include
#include <string>
#include
#include
#include
#include
#include
#include
#include
#include
#include
namespace sc &#61; boost::statechart;class EvStartStop : public sc::event
{
};
class EvReset : public sc::event
{
};/*虚类&#xff0c;用于状态机获取状态*/
class IElapsedTime
{public:virtual double elapsedTime() const &#61; 0;virtual ~IElapsedTime(){};
};class Active;
/*秒表&#xff0c;状态机*/
class StopWatch : public sc::state_machine
{public:double elapsedTime() const{return state_cast<const IElapsedTime &>().elapsedTime();}
};class Stopped;
/*活动状态*/
class Active : public IElapsedTime, public sc::state
{public:typedef sc::transition
};/*计时状态*/
class Running : public IElapsedTime, public sc::state
{public:typedef sc::transition
};/*停止状态*/
class Stopped : public IElapsedTime, public sc::state
{public:typedef sc::transition
{StopWatch myWatch;myWatch.initiate();cout <<"---" << endl;myWatch.process_event(EvStartStop());for(int i &#61; 0; i <10; i&#43;&#43;){boost::this_thread::sleep(boost::posix_time::seconds(1)); //休眠1秒std::cout <<"time:" <
}
运行效果如下&#xff1a;
Entry Active
Entry Stopped
---
Exit Stopped
Entry Running
time:1
time:2
time:3
time:4
time:5
time:6
time:7
time:8
time:9
time:10
Exit Running
Entry Stopped
current time:10
---
Exit Stopped
Exit Active
Entry Active
Entry Stopped
reset time:0
---
Exit Stopped
Exit Active