Signal ID to function call in state machines


Mapping Signal IDs to function calls

The state machine pattern assumes, that function calls are made by each incoming signal. But what if the signals exist only as a number or ID? How is the ID transformed into a function call? Of course, you could simply write a switch case, converting the integer ID into a function call. But  switch cases "smell" (look into Martin Fowlers book on Refactoring).

This example uses the function process(Signal s) (line 61, lines 76 and 77) to process the signal which is given as an ID.  Look at line 63 where the respective function is being called (omit lines 62 and 64 in your production code). It´s just one line of code: No switch case. How is this done?

funcArray is an std::vector of member function pointers. The signal ID is simply the index of the respective function in the function pointer array. 

The std::vector is initialized in line 67. Lambdas need to be used to store member functions in the function pointer array.

The code also shows how to print the current state using the build-in tool typeinfo.

The code below should compile using the old C++03.

Please write comments on what you think and how this could be improved.

 

C++03 Source Code Example

Authors:

Nils Schönherr und Stephan Pareigis

Leave a comment

Your email address will not be published. Required fields are marked *