In this section requirements to user-defined types and handlers are described. The library tries to check in compile time whether these requirements are met, so in many cases an incorrect code will simply not compile. But still it is possible to compile an invalid code and the error will be seen only in run time. Therefore reading this section is highly recommended.
fsm::state class template instance. A state may
inherit other classes in any way, such inheritance is not noticed by the library. It is guaranteed that
if several states of a single state machine virtually inherit the same base class then this virtual
base class is shared between the states (i.e. the state machine object will contain only one instance
of the virtual base class).fsm::state
class template definition.
void.const qualifier and
a reference may be added to the event type before passing to an event handler. Generally, users should not
differentiate event types only by cv-qualifiers and referenceness.
on_process taking a single mandatory argument (an event) and returning a value implicitly convertible to
the state machine return value (or void if the machine returns nothing). An event handler may
be template if all template parameters are deducable from its argument.
template< typename StateT, typename EventT > struct is_applicable;void transit(state type& state, event type const& evt);is_applicable
should have a static boolean constant value
that equals true if this element of transitions map may be used to
perform the transition or false otherwise. The predicate takes
two template parameters: the current state (StateT) type and the event type
(EventT).true from the
predicate. If it finds one, it stops the search and uses this element as a
transition rule.transit should take a reference to the current state
and an event as arguments. This function should perform all needed actions to switch to
target state (call to the switch_to method in the current state in the simpliest
case). It must be noted that this function may perform no transition in which case the event
will be passed into the current state.is_applicable
predicate of the element returned true. If the function throws, the
exception is propagated to the FSM's caller.
void on_enter_state();void on_leave_state();switch_to method, no transition is made.void on_reset();switch_to)
during execution. It is not specified which state is current while executing these handlers.
return_type (any const&, std::type_info const&, fsm::state_id_t);
static std::string const& get_state_name();locking_state_machine class template. User should provide
synchronization to safely construct the state name, if needed.
state_id_t
The state_id_t type is used by the library to identify states within a complete state machine. This type
is defined in exceptions.hpp file in boost::fsm namespace. The type gives following guaranties:
stateSynopsis:
template< typename StateT, typename StateListT, typename RetValT = void > class state { public: // Types typedef RetValT return_type; // Constants static const unsigned int states_count = number of states in StateListT sequence; static const state_id_t state_id = implementation defined identifier; // Public methods state_id_t get_current_state_id() const; std::type_info const& get_current_state_type() const; std::type_info const& get_state_type(state_id_t state_id) const; std::string const& get_current_state_name() const; std::string const& get_state_name(state_id_t state_id) const; void on_enter_state(); void on_leave_state(); void on_reset(); static std::string const& get_state_name(); protected: // Protected methods (available from state implementation) template< typename AnotherStateT > void switch_to(); void switch_to(state_id_t next_state_id); };
#include <boost/fsm/state_machine.hpp>boost::fsm namespace.
StateT. A final state type that publicly inherits this state instantiation.
The final state class may have other base classes even between it and the state instantiation.
The StateT class must be in the StateListT type sequence.
StateListT. An MPL type sequence that enlists all states the state machine consists of.RetValT. A return type of the state machine. Every on_process event handler must
return a value convertible to this type.
The state class template only provides return_type type that reflects the RetValT template parameter.
states_count. The static constant equals to number of states in the StateListT template parameter.state_id. A unique in scope of a complete state machine identifier that may be used to identify the state.As seen in synopsis, constructors and assignment operator are trivial.
state_id_t get_current_state_id() const;
Returns: The return value is an identifier of state in which the state machine persists at the point of call. In most cases this call merely returns the identifier of the state from which the call is made. But this accessor may make sense if being called after calling to aswitch_tomodifier.
Complexity:O(1).
Exception safety: Does not throw.
std::type_info const& get_current_state_type() const;
Returns: Equivalent toget_state_type(get_current_state_id());.
Complexity:O(1).
Exception safety: Does not throw.
std::type_info const& get_state_type(state_id_t state_id) const;
Returns: Type information for the final state type identified withstate_id.
Complexity:O(1).
Exception safety: Throwsbad_state_idifstate_idis not valid.
std::string const& get_current_state_name() const;
Returns: Equivalent toget_state_name(get_current_state_id());.
Complexity:O(1).
Exception safety: Does not throw.
std::string const& get_state_name(state_id_t state_id) const;
Returns: The result of the static member functionget_state_namefor the final state type identified withstate_id.
Complexity:O(1).
Exception safety: Throwsbad_state_idifstate_idis not valid. Additionally, throws anything that the static member functionget_state_namemay throw.
static std::string const& get_state_name();
Returns: The returned value is a reference to a default library-generated name of the final state. The library will try to do its best to make this name human readable.
Complexity:O(1).
Exception safety: Does not throw.
void on_enter_state();
Effects: None. This empty empty handler is only used to provide optionality of the same-named handler in the final state class.
Complexity:O(1).
Exception safety: Does not throw.
void on_leave_state();
Effects: None. This empty empty handler is only used to provide optionality of the same-named handler in the final state class.
Complexity:O(1).
Exception safety: Does not throw.
void on_reset();
Effects: None. This empty empty handler is only used to provide optionality of the same-named handler in the final state class.
Complexity:O(1).
Exception safety: Does not throw.
template< typename AnotherStateT > void switch_to();
Effects: Calls toon_leave_statein the current state, then calls toon_enter_statein theAnotherStateT, then changes current state toAnotherStateTand returns. TheAnotherStateTmust be in theStateListTtype sequence.
Complexity:O(1), not including the complexity of user-providedon_enter_stateoron_leave_state.
Exception safety: Does not throw, unlesson_enter_stateoron_leave_statethrows. If it does the current state remains the same.
void switch_to(state_id_t next_state_id);
Effects: Calls toon_leave_statein the current state, then calls toon_enter_statein the target state identified withnext_state_id, then changes current state to the target state and returns.
Complexity:O(1), not including the complexity of user-providedon_enter_stateoron_leave_state.
Exception safety: Throwsbad_state_idif thenext_state_idis not valid. If eitheron_enter_stateoron_leave_statethrows the current state remains the same.
state_machineSynopsis:
template< typename StateListT, typename RetValT = void, typename TransitionListT = void > class state_machine { public: // Types typedef StateListT states_type_list; typedef RetValT return_type; typedef implementation defined MPL type sequence transitions_type_list; // Constants static const unsigned int states_count = number of states in StateListT sequence; // Constructors state_machine(); template< typename T > state_machine(T const& handler); // Public methods template< typename StateT > bool is_in_state() const; template< typename T > T& get(); template< typename T > T const& get() const; state_id_t get_current_state_id() const; std::type_info const& get_current_state_type() const; std::type_info const& get_state_type(state_id_t state_id) const; std::string const& get_current_state_name() const; std::string const& get_state_name(state_id_t state_id) const; template< typename EventT > return_type process(EventT const& evt); void reset(); template< typename T > void set_unexpected_event_handler(T const& handler); void set_default_unexpected_event_handler(); };
#include <boost/fsm/state_machine.hpp>boost::fsm namespace.
StateListT. An MPL type sequence that enlists all states the state machine consists of.RetValT. A return type of the state machine.TransitionListT. An MPL type sequence that enlists all automatic transition rules.
states_type_list. This type reflects StateListT template parameter.return_type. This type reflects RetValT template parameter.transitions_type_list. The same as TransitionListT template parameter if it is specified.
Otherwise the type is an empty MPL type sequence.
The state_machine class template defines only the states_count static constant that equals to the number of states
in the StateListT template parameter.
state_machine();
Effects: Default constructs the state machine. The current state right after construction is the first state in theStateListTtype sequence.
Complexity:O(states_count)for the first object construction,O(1)for the consequent objects construction, not including the complexity of states construction.
Exception safety: Does not throw, unless a state constructor throws.
template< typename T > state_machine(T const& handler);
Effects: Equivalent to default-constructingstate_machineobject and immediately callingset_unexpected_event_handler(handler)on it.
Complexity:O(states_count)for the first object construction,O(1)for the consequent objects construction, not including the complexity of states construction.
Exception safety: Does not throw, unless a state constructor orset_unexpected_event_handlerthrows.
template< typename StateT > bool is_in_state() const;
Returns: Equivalent toget_current_state_id() == StateT::state_id.
Complexity:O(1).
Exception safety: Does not throw.
template< typename T > T& get();template< typename T > T const& get() const;
Returns: A (constant) reference to state or states' public base classT. IfTis the public base class of more than one state then it must be a virtual base to disambiguate the instance to return reference to.
Complexity:O(1).
Exception safety: Does not throw.
state_id_t get_current_state_id() const;std::type_info const& get_current_state_type() const;std::type_info const& get_state_type(state_id_t state_id) const;std::string const& get_current_state_name() const;std::string const& get_state_name(state_id_t state_id) const;
See the description of these methods in the state class template reference.
template< typename EventT > return_type process(EventT const& evt);
Effects: First performs a lookup in the automatic transitions map for a transition rule (see synopsis of thetransitionclass template to see the required members of a transition rule). If the rule is found its static member functionis_allowedis called withevtto check weither the transition is allowed to take place. If the result is positive the transition to the target state (equivalent to call toswitch_to< target state >()in the current state).
After that a call toon_processin the target (current, if no transition took place) state is made. Theevtobject is passed as a single argument of theon_processhandler.
If no appropriateon_processhandler found to takeevtas an argument the unexpected event handler is invoked.
Returns: The result of theon_processhandler or unexpected event handler call, whichever occured.
Complexity:O(states_count)for the first call for each distinctive typeEventT,O(1)for the consequent calls on this or any other instances of the state machine. The estimations are made not including the complexity of any user-defined handlers involved during the call.
Exception safety: Does not throw, unless a user-defined handler throws.
void reset();
Effects: Calls toon_resethandlers in every state. Then silently (with no handlers called) resets to the initial state.
Complexity:O(1), not including the complexity ofon_resethandlers.
Exception safety: Does not throw. Any exceptions thrown from theon_resethandlers are suppressed.
template< typename T > void set_unexpected_event_handler(T const& handler);
Effects: Sets a function object or a function pointerhandleras an unexpected events processing routine. If by the time of the call there already was set an unexpected events handler the old handler is lost.
This routine will be called each time when the library discovers that an eventeof given typeEcannot be processed in the current stateSbecause there is noon_processhandler method in the state that could accept the event. Thereforehandlermust provideoperator()with the following signature (in case ifhandleris a function pointer this must be the function's signature):
return_type (boost::any const& evt, std::type_info const& state_type, state_id_t state_id);While being calledhandler's arguments will be filled as follows:evtwill containe,state_typewill containtypeid(S),state_idwill containS::state_id. The return value ofhandler, if it returns normally, will be returned fromprocessmethod of the state machine.
Complexity:O(1).
Exception safety: May throw ifboost::functionassignment operator throws. This may bestd::bad_allocin case of insufficient memory.
void set_default_unexpected_event_handler();
Effects: Restores the default library behaviour on unexpected events - throwing anunexpected_eventexception.
Complexity:O(1).
Exception safety: Does not throw.
locking_state_machineSynopsis:
template< typename StateListT, typename RetValT = void, typename TransitionListT = void, typename MutexT = unspecified, typename LockerT = typename MutexT::scoped_lock > class locking_state_machine : public state_machine< StateListT, RetValT, TransitionListT > { public: // Inherits all members from the base class // Types typedef MutexT mutex_type; typedef LockerT scoped_lock; // Public methods mutex_type& get_mutex() const; };
#include <boost/fsm/locking_state_machine.hpp>boost::fsm namespace.
StateListT, RetValT and TransitionListT types have the same semantics
as for the state_machine class template.
MutexT. A mutex type to be used to lock the state machine object. The default mutex type
is a recursive mutex on platforms that support multithreading (currently, pthreads and WinAPI
threading APIs are supported by default). A Boost.Thread mutex model
may be used in this type.LockerT. A scoped locker type used to lock and unlock the mutex. With given object m
of type MutexT the expression LockerT l(m); should be valid and result in locking m
until destruction of l. By default a scoped waiting locker is used (in other words, it puts the thread
into sleep if the mutex is already locked by another thread).
A Boost.Thread scoped lock model may be used in this type.mutex_type& get_mutex() const;
Returns: A reference to mutex object used to synchronize threads.
Complexity:O(1).
Exception safety: Does not throw.
As you may see the locking_state_machine class template provides almost the same interface as
state_machine does. These methods of the interface
also provide automatic mutex locking:
template< typename EventT > return_type process(EventT const& evt);. Locks for the whole event processing.void reset();. Locks for the whole reset process.template< typename T > void set_unexpected_event_handler(T const& handler);. Locks to make handler copying thread-safe.void set_default_unexpected_event_handler();. Locks to make previous handler destruction thread-safe.on_process, on_reset, on_enter_state and on_leave_state state handlers are executed in one thread concurrently.transit static members of transitions are executed in one thread concurrently.set_unexpected_event_handler is executed in one thread concurrently.get_state_name static member function of the state is left unlocked. If he or she overrides the default
implementation of get_state_name in the fsm::state class, the user might want to put additional effort to make his or her
implementation thread-safe.
basic_transitionSynopsis:
template< typename NextStateT > struct basic_transition { // Public methods template< typename CurrentStateT, typename EventT > static void transit(CurrentStateT& state, EventT const& evt); };
#include <boost/fsm/transition.hpp>boost::fsm namespace.
NextStateT type is a final state type to perform transition to if all transition rule checks pass.
Since no objects of transition rules are to be created no specific constructors or operators are provided.
template< typename CurrentStateT, typename EventT > static void transit(CurrentStateT& state, EventT const& evt);
Effects: Equivalent tostate.switch_to< NextStateT >().
Complexity:O(1).
Exception safety: Does not throw unless any user handlers throw.
transitionSynopsis:
template< typename CurrentStateT, typename EventT, typename NextStateT > struct transition : public basic_transition< NextStateT > { template< typename StateT, typename EvtT > struct is_applicable; };
#include <boost/fsm/transition.hpp>boost::fsm namespace.
CurrentStateT. A final state type in which state machine must persist the transition to take place. This
template parameter may also be any_state to indicate that the transition rule is actual in all states.EventT. An event type that triggers the transition.NextStateT. A final state type to perform transition to if all transition rule checks pass.template< typename StateT, typename EvtT > struct is_applicable;
This class template is an MPL-style predicate that has static member boolean constantvalue. The constant equalstrueif both these conditions are met:Otherwise the
StateTequals toCurrentStateTorCurrentStateTequals toany_stateEvtTequals toEventTvalueconstant equals tofalse.
Since no objects of transition rules are to be created no specific constructors or operators are provided.
event and event_cSynopsis:
template< typename TagT, typename T0 = void, ..., typename Tn = void > struct event : public tuple< significant types from T0 to Tn > { // Types typedef TagT tag_type; typedef tuple< significant types from T0 to Tn > tuple_type; // Constructors event(); explicit event(tuple_type const& that); // Assignment event& operator= (event const& that); template< typename U > event& operator= (U const& that); // Public methods tuple_type& get_tuple(); tuple_type const& get_tuple() const; }; template< int TagV, typename T0 = void, ..., typename Tn = void > struct event_c : public event< mpl::int_< TagV >, T0, ..., Tn > { // Inherits all members from the base class }; // Helper construction functions template< typename TagT, typename ArgT0, ..., typename ArgTm > event< TagT, adopted ArgT0 - ArgTm types > make_event(ArgT0 const& arg0, ..., ArgTm const& argm); template< int TagV, typename ArgT0, ..., typename ArgTm > event_c< TagV, adopted ArgT0 - ArgTm types > make_event(ArgT0 const& arg0, ..., ArgTm const& argm);
#include <boost/fsm/event.hpp>boost::fsm namespace.
TagT or TagV. A tag type or value to differentiate event and event_c
types with the same set of parameters.T0 - Tn. Event argument types. The number of these types is limited with macro
BOOST_FSM_MAX_EVENT_ARGS. This macro defaults to 10 and may be redefined by user, though it should not exceed
the maximum number of boost::tuple template parameters.
tag_type. This type reflects the TagT template parameter.tuple_type. The type of boost::tuple instance used to hold the event's arguments. Its template parameters
are formed based on the T0 - Tn template parameters with some adoptions.
event();event_c();
Effects: Default constructs the event. Event arguments are default constructed in the inheritedtupleinstance.
Complexity:O(1), not including thetupleinstance construction complexity.
Exception safety: Does not throw, unless thetupleconstructor throws.
explicit event(tuple_type const& that);explicit event_c(tuple_type const& that);
Effects: Constructs the event withthatarguments. Thethatargument is passed totuple's constructor.
Complexity:O(1), not including thetupleinstance construction complexity.
Exception safety: Does not throw, unless thetupleconstructor throws.
event& operator= (event const& that);template< typename U > event& operator= (U const& that);event_c& operator= (event_c const& that);template< typename U > event_c& operator= (U const& that);
Effects: Passes thethatargument totuple's assignment operator.
Returns:*this
Complexity:O(1), not including thetupleassignment operator.
Exception safety: Does not throw, unless thetupleoperator throws.
tuple_type& get_tuple();tuple_type const& get_tuple() const;
Returns:*this.
Complexity:O(1).
Exception safety: Does not throw.
template< typename TagT, typename ArgT0, ..., typename ArgTm >
event< TagT, adopted ArgT0 - ArgTm types > make_event(ArgT0 const& arg0, ..., ArgTm const& argm);template< int TagV, typename ArgT0, ..., typename ArgTm >
event_c< TagV, adopted ArgT0 - ArgTm types > make_event(ArgT0 const& arg0, ..., ArgTm const& argm);
Returns: A constructed event object witharg0-argmarguments. IfArgTitype is aboost::reference_wrapperinstance it is converted to a corresponding reference type to instantiateeventorevent_c. This is done to simplify the event usage in theon_processhandlers.
Complexity:O(1).
Exception safety: Does not throw, unless theevent's constructor throws.
fsm_errorSynopsis:
class fsm_error : public std::exception { public: // Constructors fsm_error(std::type_info const& State, state_id_t StateID); fsm_error(std::string const& StateName, std::type_info const& State, state_id_t StateID); // Destructor ~fsm_error() throw(); // Public methods std::type_info const& current_state_type() const; state_id_t current_state_id() const; const char* what() const throw(); };
#include <boost/fsm/exceptions.hpp>, automatically included in boost/fsm/state_machine.hpp.boost::fsm namespace.
fsm_error(std::type_info const& State, state_id_t StateID);fsm_error(std::string const& StateName, std::type_info const& State, state_id_t StateID);
Effects: Constructs the exception object. The arguments are saved in the exception object.
Complexity: ArgumentsStateNameandStateIDare copied, a reference toStateis bound in the exception object.
Exception safety: Does not throw, unless thestd::stringcopy constructor throws.
~fsm_error() throw();
Effects: Destroys the exception object.
Complexity: May involvestd::stringobjects destruction, if they were constructed through the object's lifetime.
Exception safety: Does not throw.
std::type_info const& current_state_type() const;
Returns: The result value equals to theStateargument of thefsm_errorconstructor. It is a type information of the final state in which the error have occured.
Complexity:O(1).
Exception safety: Does not throw.
state_id_t current_state_id() const;
Returns: The result value equals to theStateIDargument of thefsm_errorconstructor. It is an identifier of the final state in which the error have occured.
Complexity:O(1).
Exception safety: Does not throw.
const char* what() const throw();
Returns: The error description.
Complexity:O(1).
Exception safety: Does not throw.
bad_state_idSynopsis:
class bad_state_id : public fsm_error { public: // Constructors bad_state_id(state_id_t BadStateID, std::type_info const& State, state_id_t StateID); bad_state_id( state_id_t BadStateID, std::string const& StateName, std::type_info const& State, state_id_t StateID); // Destructor ~bad_state_id() throw(); // Public methods state_id_t state_id() const; const char* what() const throw(); };
#include <boost/fsm/exceptions.hpp>, automatically included in boost/fsm/state_machine.hpp.boost::fsm namespace.
bad_state_id(state_id_t BadStateID, std::type_info const& State, state_id_t StateID);bad_state_id(state_id_t BadStateID, std::string const& StateName, std::type_info const& State, state_id_t StateID);
Effects: Constructs the exception object. The arguments are saved in the exception object.
Complexity: ArgumentsBadStateID,StateNameandStateIDare copied, a reference toStateis bound in the exception object.
Exception safety: Does not throw, unless thestd::stringcopy constructor throws.
~bad_state_id() throw();
Effects: Destroys the exception object.
Complexity: May involvestd::stringobjects destruction, if they were constructed through the object's lifetime.
Exception safety: Does not throw.
state_id_t state_id() const;
Returns: The result value equals to theBadStateIDargument of thebad_state_idconstructor. It is an invalid state identifier that caused the exception.
Complexity:O(1).
Exception safety: Does not throw.
const char* what() const throw();
Returns: The error description.
Complexity: May involve memory allocations while constructing the error message text.
Exception safety: Does not throw.
unexpected_eventSynopsis:
class unexpected_event : public fsm_error { public: // Constructors unexpected_event(any const& Event, std::type_info const& State, state_id_t StateID); unexpected_event( any const& Event, std::string const& StateName, std::type_info const& State, state_id_t StateID); // Destructor ~unexpected_event() throw(); // Public methods any const& event() const; const char* what() const throw(); };
#include <boost/fsm/exceptions.hpp>, automatically included in boost/fsm/state_machine.hpp.boost::fsm namespace.
unexpected_event(any const& Event, std::type_info const& State, state_id_t StateID);unexpected_event(any const& Event, std::string const& StateName, std::type_info const& State, state_id_t StateID);
Effects: Constructs the exception object. The arguments are saved in the exception object.
Complexity: ArgumentsEvent,StateNameandStateIDare copied, a reference toStateis bound in the exception object.
Exception safety: Does not throw, unless thestd::stringorboost::anycopy constructor throws.
~unexpected_event() throw();
Effects: Destroys the exception object.
Complexity: Impliesboost::anydestruction. May involvestd::stringobjects destruction, if they were constructed through the object's lifetime.
Exception safety: Does not throw.
any const& event() const;
Returns: The result value is a copy of the event object that failed to be dispatched to anon_processhandler.
Complexity:O(1).
Exception safety: Does not throw.
const char* what() const throw();
Returns: The error description.
Complexity: May involve memory allocations while constructing the error message text.
Exception safety: Does not throw.
Copyright © 2006 Semashev Andrey
Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)