-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathreadme.html
1573 lines (1232 loc) · 50.8 KB
/
readme.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?xml version="1.0" encoding="us-ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- vim:set noexpandtab: -->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta content="text/html; charset=us-ascii" http-equiv="content-type" />
<meta name="description" content="Hierarchical state machines for C++" />
<meta name="keywords" content="C++, statechart, state machine, statemachine,
state, hierarchical state machine" />
<meta name="author" content="Eduard Hiti" />
<link rel="alternate" type="application/atom+xml" title="C++ Machine Objects" href="http://ehiti.de/machine_objects/atom.xml" />
<title>Machine Objects - Hierarchical state machines in C++</title>
<style type="text/css">
/*<![CDATA[*/
body {
font-family: Georgia, "New York", Times, serif;
font-size: 14px;
line-height: 150%;
margin: 0;
text-align: center; /* for IE */
color: #000000;
background-color: #8f8f8f;
}
#border {
border-left: 2px black solid;
border-right: 2px black solid;
border-top: 1px black solid;
border-bottom: 1px black solid;
background-color: white;
margin: auto;
width: 58em;
}
#container {
width: 50em;
text-align: justify;
margin: 2em auto;
}
em {
font-style: italic;
}
h1 {
font-family: Fixedsys, System, "Courier New", Courier, monospace;
font-size: 300%;
margin-top: 1em;
margin-bottom: 1em;
color: #802800;
text-align: center;
}
h2, h3, h4 {
margin-top: 30px;
color: #802800;
}
table {
line-height: 150%;
font-size: 14px; /* for IE */
}
a:link, a:visited {
color: blue;
}
pre {
overflow: auto;
background-color: #efefef;
color: #000099;
font-family: "Lucida Console", monospace;
line-height: 150%;
border: 1px black solid;
padding: 9px;
margin-left: 2em ;
margin-right: 2em ;
}
code {
color: #000099;
font-family: "Lucida Console", monospace;
}
.toc {
font-family: Verdana, Geneva, Arial, sans-serif;
font-size: 80%;
line-height: 150%;
width: 72%;
}
.toc a {
text-decoration: none;
}
.toc .level1 {
font-weight: bold;
}
.toc .level2 {
}
.toc .level3 {
font-size: 90%;
line-height: 150%;
font-style: italic;
}
.indent {
margin-left: 3em;
}
.boring, .note, .warning {
font-family: Verdana, Geneva, Arial, sans-serif;
border-top: 1px dotted;
border-bottom: 1px dotted;
border-color: silver;
line-height: normal;
font-size: 80%;
line-height: 150%;
text-align: left;
padding-top: 0.5em;
padding-bottom: 0.5em;
}
.boring {
margin-left: 1em;
margin-right: 1em;
}
.note, .warning {
margin-left: 1em;
margin-right: 1em;
}
.nl, .warning_label {
float: left;
color: gray;
margin-right: 0.5em;
font-weight: bold;
font-style: italic;
}
.bold {
font-weight: bold;
}
.de {
color: #6f6f6f;
}
.faq {
text-align: justify;
vertical-align: top;
font-weight: bold;
}
.versions {
font-size: 80%;
line-height: 150%;
font-family: Verdana, Geneva, Arial, sans-serif;
}
.versions > ul > li {
margin-bottom: 15px;
}
.versions > ul {
list-style-type: none;
}
/*]]>*/
</style>
</head>
<body>
<div id="border">
<div id="container">
<h1>C++ Machine Objects</h1>
<table summary="">
<tbody>
<tr>
<td class="toc">
<p><span class="bold" style="font-style: italic">Table of Contents</span></p>
<a class="level1" href="#Intro">1 Introduction</a><br />
<a class="level1" href="#Motivation">2 Motivation</a><br />
<a class="level1" href="#Installation">3 Installation</a><br />
<a class="level1" href="#Design">4 Design</a><br />
<a class="level1" href="#Doku">5 Using Machine Objects</a><br />
<div class="indent">
<a class="level2" href="#StateDefs">5.1 State Definitions</a><br />
<a class="level2" href="#Entry">5.2 Entry and Exit</a><br />
<a class="level2" href="#StateVars">5.3 State Variables</a><br />
<a class="level2" href="#Handlers">5.4 Event Handlers</a><br />
<a class="level2" href="#Transitions">5.5 State Transitions</a><br />
<div class="indent">
<a class="level3" href="#Aliases">5.5.1 Parametrized State Transitions</a><br />
</div>
<div class="indent">
<a class="level3" href="#Reflection">5.5.2 Reflection</a><br />
</div>
<a class="level2" href="#History">5.6 History</a><br />
<a class="level2" href="#Machine">5.7 Machine Creation</a><br />
<div class="indent">
<a class="level3" href="#MManaging">5.7.1 Managing Machines</a><br />
<a class="level3" href="#Snapshots">5.7.2 Machine Snapshots</a><br />
</div>
<a class="level2" href="#Dispatch">5.8 Event Dispatch</a><br />
<div class="indent">
<a class="level3" href="#Internal">5.8.1 Internal Event Dispatch</a><br />
</div>
<a class="level2"
href="#Advanced">5.9 Advanced Topics</a><br />
<div class="indent">
<a class="level3"
href="#Templates">5.9.1 Template States</a><br />
</div>
</div>
<a class="level1" href="#Conclusion">6 Conclusion</a><br />
<a class="level1" href="#FAQ">7 FAQ</a><br />
<a class="level1" href="#Version">8 Version History</a><br />
</tr>
</tbody>
</table>
<h2 id="Intro">1 Introduction</h2>
<p>The <em>Machine Objects</em> class library allows the creation of state
machines based on the "State" design pattern in plain C++. It extends the
pattern with the option to create hierarchical state machines, making it
possible to convert the popular UML statechart notation to working code in a
straightforward way. Other features are entry and exit actions, state
histories and state variables.</p>
<p>The <i>"just show me code"</i> link to an example state machine:
<a href="Microwave.cpp" >Microwave</a></p>
<div class="boring">
For license information please see the <a href=
"http://www.opensource.org/licenses/mit-license.php">MIT License</a> or
the header in file <a href="Macho.hpp" >Macho.hpp</a>.
<p>Homepage is at <a href="http://ehiti.de/machine_objects" >http://ehiti.de/machine_objects</a>
<br />
Feedback goes to <a href="mailto:[email protected]" >[email protected]</a></p>
<p>Copyright 2005 by Eduard Hiti.</p>
You are encouraged to provide any changes, extensions and
corrections for this software to the author for inclusion into future
versions.
</div>
<h2 id="Motivation">2 Motivation</h2>
<p>In my experience as software developer I have found the
<a href="http://home.earthlink.net/%7Ehuston2/dp/state.html">State</a>
design pattern to be very useful. It enables implementing the important
concept of state machines with common programming language features. By
using only basic language mechanisms it is easy to apply in real-life
software development.</p>
<p>Another important property that stems from this simplicity is
orthogonality: the pattern can be combined with other design
elements, patterns and idioms in arbitrary ways.</p>
<p>In contrast stand tool supported approaches to state machine
creation (of which there is no shortage). Based on code generators and
graphical editors, they tend to generate incomprehensible code as product
and forfeit orthogonality by necessarily being outside the domain of the
programming language.</p>
<p>Unfortunately the "State" pattern is limited in scope because it does
not allow for hierarchical state machines. This is regrettable because
flat state machines tend to become unwieldy when getting more elaborate,
for the sheer number of states they produce.</p>
<p>Hierarchical state machines as defined by the statechart notation
alleviate this problem by providing an additional structural element with
the grouping of states into hierarchies, thereby facilitating the sharing
of common logic between states.</p>
<p>The "State" pattern in its original form is not capable of modeling state
hierarchies. The <em>Machine Objects</em> class library (in short
<em>Macho</em>) extends the concept with this possibility, while keeping the
properties of simplicity (where possible) and tool independence from its
inspiration.</p>
<h2 id="Installation">3 Installation</h2>
<p>The class library as such does not need to be installed.
Just include the header file <a href="Macho.hpp" >Macho.hpp</a>
and add the file <a href="Macho.cpp" >Macho.cpp </a> to your make
file or project definition.</p>
<p>Prerequisite however is a C++ compiler with sane support for templates
(like gcc 2.95+ or MSVC7+). For the obsolete but inexplicably popular
compiler MSVC6 a special version of the library is provided.</p>
<p>Included are the example state machines <em>HelloWorld</em>,
<em>Example</em>, <em>Microwave</em> and <em>Test</em>. To make the
examples run just compile them in the directory they are in, for
example:</p>
<pre>
# GCC
g++ -o microwave Microwave.cpp Macho.cpp
# MSVC7
cl /EHsc Microwave.cpp Macho.cpp
</pre>
<h2 id="Design">4 Design</h2>
<p>The following descriptions assume some knowledge of the statechart
notation. For more information see
<a href= "http://wikipedia.org/wiki/Statechart">Wikipedia</a>
.</p>
<p>Starting point is the "State" design pattern. The essence of the
pattern is to represent states by classes. State transitions are
performed by instantiating objects of these classes.</p>
<p>From this perspective the constructors and destructors of state classes can
be seen as taking on the role of entry and exit actions. Object
attributes then constitute state variables. Events are dispatched by
calling methods on state objects which implement the guards, actions and
transitions of states.</p>
<p>For states to compose a hierarchy, substates must be able to take over
the event handling logic of superstates, selectively redefining it where
necessary. There exists a mechanism in C++ allowing redefinition of
behaviour on the level of methods: polymorphism through class
inheritance.</p>
<p>Modeling the substate/superstate relation with class inheritance is
problematic however: the use of constructors and destructors as entry and
exit actions is not possible anymore, neither is keeping state variables
in objects.</p>
<p>The reason is that base classes are constituent parts of deriving
classes, meaning object construction or destruction will trigger all
involved class constructors or destructors and initialize or destroy all
data members.</p>
<p>This runs counter to the semantics of entry/exit actions and state
variables, where a transition between sibling substates should not
trigger superstate entry/exit actions nor destroy superstate state
variables.</p>
<p>Our solution to this problem is to use explicit methods for state
entry and exit, being called in the correct sequence on state
transitions. State variables are kept in separate state specific data
structures which have a life cycle consistent with the hierarchy of
states.</p>
<h2 id="Doku">5 Using Machine Objects</h2>
<p>Before diving into implementation details we first define some
terminology to be used from here on.</p>
<p>By <em>state class</em> we mean the class defined to represent a
particular state. A <em>state machine</em> is a partially ordered set
of states having a common top state class. A <em>state machine instance</em>
maintains an element of that set as current state to which events can be
dispatched. A state machine's <em>event protocol</em> is the set of
events that are understood by the machine.</p>
<p>Furthermore extracts from the simple state machine defined in the
file <a href="Example.cpp" >Example.cpp</a> will be used
for illustration. It is a good idea to have a look at this file now if
you are reading this for the first time. It contains a state machine
with four states: a top state, a superstate <code>Super</code>, two
substates <code>StateA</code> and <code>StateB</code>, and a small test
run. Each state has entry/exit actions, the top state and
<code>StateA</code> have state variables and the event protocol consist
of two events, <code>event1</code> and <code>event2</code>.</p>
<h3 id="StateDefs">5.1 State Definitions</h3>
<p>A top state is defined by the macro
<code>TOPSTATE</code>:</p>
<pre>
TOPSTATE(Top) {
<span class="de">...</span>
};
</pre>
<p>Every state machine must have a top state. The top state's interface
defines the machine's event protocol: only the public virtual methods of
the top state can be event handlers.</p>
<div class="note">
<span class="nl">Note:</span>The default visibility in states is
<code>public</code>.
</div>
<p>The top state is representative for the whole state machine. All
other states of a machine are direct or indirect substates of the top
state.</p>
<div class="note">
<span class="nl">Note:</span> The top state has a <code>typedef</code> alias
<code>TOP</code> available to all states of the machine.
</div>
<p>Substates are defined by the <code>SUBSTATE</code> macro:</p>
<pre>
SUBSTATE(Super, Top) {
<span class="de">...</span>
};
</pre>
<p>This statement defines the class <code>Super</code> as substate of class
<code>Top</code>. The macro parameters are the substate's name and
the name of its superstate. The superstate can be the top state or any
other substate.</p>
<div class="note"><span class="nl">Note:</span>
A <code>typedef</code> alias <code>SUPER</code> will point to the
superstate within the substate class.
</div>
<p>Why are macros used for <em>Machine Objects</em>? The reason being
convenience only, you'll most likely agree with their use if you look at
the definitions of the macros <code>TOPSTATE</code> and
<code>SUBSTATE</code>:</p>
<pre>
#define TOPSTATE(TOP) \
struct TOP : public Macho::Link< TOP, Macho::TopBase< TOP > >
#define SUBSTATE(STATE, SUPERSTATE) \
struct STATE : public Macho::Link< STATE, SUPERSTATE >
</pre>
<p>The code is more readable and actually less error-prone (notice the
multiple use of the same macro parameter in <code>TOPSTATE</code> and
<code>SUBSTATE</code>) by using macro expansion.</p>
<p>Another macro is <code>STATE(S)</code> which MUST be invoked in every
state body:</p>
<pre>
SUBSTATE(Super, Top) {
STATE(Super)
<span class="de">...</span>
};
</pre>
<p>The macro parameter is the state's name again. With this macro some
definitions are provided in the class body (a constructor for instance).
For more details look up the macro's definition.</p>
<div class="note"><span class="nl">Note:<br/> </span>
Every state class must be instantiable (the top state as well).
This means states must not have pure virtual methods!</div>
<h3 id="Entry">5.2 Entry and Exit</h3>
<p>A state's (optional) entry and exit actions are defined this way:</p>
<pre>
<span class="de">TOPSTATE(Top) {</span>
<span class="de">...</span>
<span class="de">private:</span>
void entry();
void exit();
void init();
<span class="de">};</span>
void Top::entry() { <span class="de">...</span> }
void Top::exit() { <span class="de">...</span> }
void Top::init() { <span class="de">...</span> }
</pre>
<p>The methods <code>entry</code> and <code>exit</code> of a state are
called upon transitioning into or out of it. The sequence of calls for a
state transition is as follows:</p>
<ul>
<li>
<p>First the exit action of the current state is called and then
those of its superstates (in bottom up order), up to and excluding
the first superstate that is also superstate of the new state.</p>
</li>
<li>
<p>Then entry actions of superstates of the new state are called, top
down from the first superstate that is not also a superstate of the
previous state. Finally the entry action of the new state is
called.</p>
</li>
</ul>
<div class="note"><span class="nl">Note:<br/> </span>
From this follows that self transitions (where the new state is the
same state as the current state) will trigger that state's exit and entry
actions.
</div>
<p>Entries and exits may NOT initiate new state transitions (doing otherwise
will cause an assertion).</p>
<p>The method <code>init</code> defines a special kind of entry action:
Upon state transition, entry actions of the new state and its superstates
are triggered; <code>init</code> however is called only on the one state
the transition actually goes to (after its entry action is performed).</p>
<p>With <code>init</code> initial transitions of states can be
implemented, where a superstate immediately enters a substate on
entry (like the top state in <em>Example</em>). This implies that init
actions ARE in fact allowed to initiate state transitions (but only to
substates). Transitioning to a state in <code>init</code> will trigger that
new state's <code>init</code> method in turn.</p>
<p>Constructors or destructors can not be used for state classes: if you
need to make initializations, do them in entry actions or box
constructors.</p>
<div class="note"><span class="nl">Note:<br/> </span>
It is recommended that you put the methods <code>exit</code>,
<code>entry</code> and <code>init</code> into the <code>private</code>
section of your classes, at least for the top state, so that they are
not part of the event protocol.
</div>
<h3 id="StateVars">5.3 State Variables</h3>
<p>State variables allow states to accumulate information from the events
they have received in the past. This information is maintained in the scope
of the associated state: the variables of a superstate are accessible to that
state or any of its substates. Substates have full access to state
variables of their superstates.</p>
<div class="note"><span class="nl">Note:<br/> </span>
Since every state is a substate of the top state, top state variables
are accessible to all states of a machine.
</div>
<p>This is how state variables are defined:</p>
<pre>
<span class="de">TOPSTATE(Top) {</span>
struct Box {
Box() : data(0) {}
long data;
};
<span class="de">STATE(Top)</span>
<span class="de">...</span>
<span class="de">};</span>
</pre>
<p>State variables are contained in a data type named <code>Box</code>
nested into the state class (the type name <code>Box</code> is
mandatory).</p>
<div class="note"><span class="nl">Note:<br/> </span>
The box definition must appear BEFORE the use of the
<code>STATE</code> macro.
</div>
<p>The box type must be default constructable (means: has a default
constructor). Apart from this requirement the box type can be any regular
C++ type. It could even be a simple typedef:</p>
<pre>
<span class="de">TOPSTATE(Top) {</span>
typedef int Box;
<span class="de">STATE(Top)</span>
<span class="de">...</span>
<span class="de">};</span>
</pre>
<p id="Persistent">A box is created before its state is entered (before
the call to <code>entry</code>) and by default destroyed after the state
is left (after the call to <code>exit</code>). By marking a state class
with the <code>PERSISTENT</code> macro, you can override this default
behaviour and have boxes survive state transitions:</p>
<pre>
<span class="de">SUBSTATE(StateA, Top)
struct Box {
...
};
STATE(StateA)</span>
PERSISTENT()
<span class="de">...
};
</span>
</pre>
<p>Persistent boxes are created once at first entry of their state and
exist for as long as the state machine instance itself exists.</p>
<p>A state's box is accessed by calling the method <code>box</code>,
which returns a reference to the state's box object:</p>
<pre>
<span class="de">void StateA::event1(int i) {</span>
<span class="de">...</span>
cout << box().data;
<span class="de">...</span>
<span class="de">}</span>
</pre>
<p>Superstate boxes are available by qualifying the <code>box</code>
method with the superstate's name:</p>
<pre>
<span class="de">void StateB::event2(long l) {</span>
<span class="de">...</span>
cout << TOP::box().data;
<span class="de">...</span>
<span class="de">}</span>
</pre>
<p>In this example the top state's box is accessed.</p>
<h3 id="Handlers">5.4 Event Handlers</h3>
<p>As mentioned the event protocol of a state machine is defined by its
top state public interface:</p>
<pre>
TOPSTATE(Top) {
<span class="de">...</span>
virtual void event1(int i) {}
virtual void event2(long l) {}
<span class="de">...</span>
};
</pre>
<p>The <em>Example</em> state machine understands the events
<code>event1</code> and <code>event2</code>: events are named like their
event handler methods.</p>
<p>Event handlers are simple C++ methods and may have arbitrary parameters:</p>
<pre>
<span class="de">SUBSTATE(StateA, Super) {</span>
<span class="de">...</span>
void event1(int i);
<span class="de">...</span>
<span class="de">};</span>
void StateA::event1(int i) { <span class="de">...</span> }
</pre>
<p>This example defines the event handler for <code>event1</code> in
<code>StateA</code>. The method should implement all the logic to handle the
event.</p>
<div class="note"><span class="nl">Note:<br/> </span>
Event handlers may have return values.
</div>
<p>The top state event handlers define the default behaviour for the
whole state machine. If there is no meaningful implementation for an
event handler at top level, the handler could either</p>
<ul>
<li>be implemented empty: no reaction to event is then default.</li>
<li>signal some error (for example with <code>assert(false)</code>):
not handling the event will be a runtime error now.</li>
</ul>
<h3 id="Transitions">5.5 State Transitions</h3>
<p>State transitions are made by calling the method <code>setState</code>
inside an event handler:</p>
<pre>
<span class="de">void StateA::event1(int i) {</span>
<span class="de">...</span>
setState<StateB>();
<span class="de">}</span>
</pre>
<p>The template parameter to <code>setState</code> is the new state to be
entered.</p>
<div class="note"><span class="nl">Note:<br/> <br/> </span>
We recommend that you do not define event handlers inline to your
state class definitions.<br/>The reason is that C++ needs a complete
definition of a class to be used as template parameter, and that may not
be the case for the classes you want to <code>setState</code> to in
inline event handlers.
</div>
<p>The state transition takes place AFTER control flow leaves the event
handler. It is therefore possible to do meaningful work even after
calling <code>setState</code> (all involved objects are still alive). It
is however not allowed to call <code>setState</code> multiple times with
different states in a single event handler run: this will assert on
you!</p>
<p>To allow for parametrization of target states <code>setState</code> can
take up to six parameters of arbitrary type:</p>
<pre>
setState<StateB>("Some text", 42, true);
</pre>
<p>The arguments provided to <code>setState</code> are used to
invoke an <code>init</code> method of the target state with matching
signature:</p>
<pre>
<span class="de">void StateB::init(</span>const char *, int, bool<span class="de">) { ... }</span>
</pre>
<p>If no matching <code>init</code> method is provided a (template
mess) compile time error will result.</p>
<div class="note">
<span class="nl">Note:<br/> </span>
The <code>setState</code> method uses type inference to determine the types of
its parameters. Since type inference is somewhat limited in C++ you must
sometimes disambiguate arguments by casting to avoid type errors.
</div>
<h4 id="Aliases">5.5.1 Parametrized State Transitions</h4>
<p>The target of a state transition can also be provided as a runtime
value:</p>
<pre>
<span class="de">setState(</span>State<StateA>()<span class="de">);</span>
</pre>
<p>or alternatively</p>
<pre>
<span class="de">setState(</span>StateA::alias()<span class="de">);</span>
</pre>
<p>These examples create objects of type <code>Alias</code> to represent the
state given as template parameter. Objects of this type can also be stored for
later use:</p>
<pre>
Alias state = State<StateA>();
<span class="de">...</span>
setState(state);
</pre>
<p>The ability to pass around and store state aliases makes it possible to
create reusable code by parametrizing state relationships.</p>
<p>State aliases can also be provided with arguments for initialization of
the target state on transition:</p>
<pre>
<span class="de">Alias s = </span>State<StateA>("Some text", 42, true)<span
class="de">;</span>
</pre>
<p>For these arguments the same specifics as for <code>setState</code> above
apply.</p>
<h4 id="Reflection">5.5.2 Reflection</h4>
<p>To allow for runtime decisions on state relationships these can be
inspected at runtime:</p>
<pre>
<span class="de">// Read like this: StateA "is child of" Super</span>
<span class="de">assert(</span>StateA::isChild(Super::alias())<span class="de">);</span>
<span class="de">// Read like this: Super "is parent of" StateA</span>
<span class="de">assert(</span>Super::isParent(StateA::alias())<span class="de">);</span>
</pre>
<p>The same can be done with state aliases:</p>
<pre>
<span class="de">Alias stateA = StateA::alias();
Alias super = Super::alias();</span>
<span class="de">assert(</span>stateA.isChild(super)<span class="de">);</span>
<span class="de">assert(</span>super.isParent(stateA)<span class="de">);</span>
</pre>
<div class="note">
<span class="nl">Note:</span>A state is both child and parent of itself.
</div>
<p>State equality is determined as expected:</p>
<pre>
<span class="de">assert(</span>Super::alias() == Super::alias()<span class="de">);</span>
<span class="de">assert(</span>stateA != super<span class="de">);</span>
</pre>
<div class="note">
<span class="nl">Note:</span>Transition parameters are not considered then
testing for equality.
</div>
<h3 id="History">5.6 History</h3>
<p>It is possible for a superstate to remember a previously entered
substate. This history state can be reentered later with a special state
transition.</p>
<p>History for a state is enabled by invoking the macro
<code>HISTORY</code> or <code>DEEPHISTORY</code> in the state
definition:</p>
<pre>
<span class="de">SUBSTATE(Super, Top) {</span>
<span class="de">STATE(Super)</span>
HISTORY()
<span class="de">...</span>
<span class="de">};</span>
</pre>
<p>Use of <code>HISTORY</code> selects the shallow history strategy,
whereby only direct substates of a superstate are remembered.
<code>DEEPHISTORY</code> remembers even the substates of substates.</p>
<div class="note"><span class="nl">Note:<br/> </span>
Keep in mind that by default state boxes are not saved but rather
instantiated anew for reentered history states (to override use the
<a href="#Persistent"><code>PERSISTENT</code></a> macro)!
</div>
<p>The history of a state can be specified as target of a state
transition:</p>
<pre>
setStateHistory<Super>();
</pre>
<p>This example will enter the history state of <code>Super</code>. Entry
actions of all involved states will be invoked, with a final call to
the parameterless <code>init</code> method of the actual history state. If
no history information is available (because the state has not been entered
yet or history was not enabled), <code>Super</code> itself is the target of
the transition.</p>
<div class="note"><span class="nl">Note:<br/> </span>
It is not possible to provide transition parameters to
<code>setStateHistory</code> because the exact target of the transition
is not determinable at compile time.
</div>
<p>History information can also be inspected directly:</p>
<pre>
Alias s = Super::history(machine);
</pre>
<p>A call to a state's static method <code>history</code> with a machine
instance as argument will return the current history of the specified state
at the moment of the call for the specified machine instance. If the state
has no history information available an alias of the state itself is
returned.</p>
<div class="note"><span class="nl">Note:<br/> </span>
To get the current machine instance in an event handler call the
method <code>machine()</code>.
</div>
<p>Similar but slightly different is this special alias:
<pre>
Alias h = StateHistory<Super>(machine());
</pre>
<p>This alias will keep pointing to the history of <code>Super</code>, not
just the history state at the moment of alias creation. This means that the
alias can represent different states in its life, depending on the changes
to the history of <code>Super</code>.</p>
<p>Consequently the statement</p>
<pre>
setStateHistory<Super>();
</pre>
<p>and this statement:</p>
<pre>
Alias state = StateHistory<Super>(machine());
<span class="de">...</span>
setState(state);
</pre>
<p>are equivalent.</p>
<div class="note"><span class="nl">Note:<br/> </span>
The <code>StateHistory</code> alias becomes invalid when the
associated machine instance has shutdown.
</div>
<h3 id="Machine">5.7 Machine Creation</h3>
<p>A state machine instance is created by instantiating a machine
object:</p>
<pre>
Macho::Machine<Example::Top> m();
</pre>
<p>The class <code>Machine</code> is a template class in namespace
<code>Macho</code>; its template parameter is the top state of the state
machine to be run.</p>
<p>The top state is immediately entered and initialized upon machine
creation (<code>entry</code> and <code>init</code> are called).</p>
<p>The <code>Machine</code> constructor takes as optional parameter a box
for the top state:</p>
<pre>
<span class="de">Macho::Machine<Example::Top> m(</span>new Example::Top::Box(42)<span class="de">);</span>
</pre>
<p>This allows parametrization of a state machine on startup.</p>
<p>An alias can be used to specify a different start state:</p>
<pre>
Machine<Top> m(State<Example::StateA>());
</pre>
<p>The machine instance will enter the argument state with all appropriate
entry and init actions being executed.</p>
<p id="shutdown_">Upon destruction of the machine object the current sub- and
superstates up to and including the top state are exited correctly and
their boxes destroyed.</p>
<div class="note"><span class="nl">Note:<br/> </span>
You can override this behaviour by implementing the predefined
event handler <code>_shutdown</code> as empty method.<br />
Boxes are still destroyed of course.
</div>
<p>It is also possible to read the top state box of a running machine by
calling the <code>box</code> method of <code>Machine</code>:</p>
<pre>
cout << m.box().data;
</pre>
<div class="note"><span class="nl">Note:<br/> </span>
The method <code>box</code> of class <code>Machine</code> returns a
<code>const</code> reference to the top state box. It is therefore not
possible to change box data (you should really do this from INSIDE your
machine)!
</div>
<p>An alias of the machine's current state can be obtained by calling the
method <code>currentState</code>:</p>
<pre>
<span class="de">assert(</span>m.currentState()<span class="de"> == StateA::alias());</span>
</pre>
<h4 id="MManaging">5.7.1 Managing Machines</h4>
<p>A state's history for a particular machine instance can be cleared by
calling the state's static method <code>clearHistory</code> with the
machine object as argument:</p>
<pre>
Super::clearHistory(m);
</pre>
<p id="clearHistoryDeep">This statement resets history information for
<code>Super</code> inside machine <code>m</code>, without affecting substate
history however (use <code>clearHistoryDeep</code> for this).</p>
<p>Another static method of state classes allows testing for the current
state of a machine object:</p>
<pre>
<span class="de">assert(</span>StateA::isCurrent(m)<span class="de">);</span>
</pre>
<p>The method <code>isCurrent</code> returns <code>true</code> if the
given machine object is in the specified state or any of its substates at
that moment.</p>
<div class="note">
<span class="nl">Note:</span><code>StateA::alias() == m.currentState()</code>
checks if the machine is exactly in <code>StateA</code>.
</div>