sanders
sanders

Reputation: 133

What's the best way of implementing a finite state machine in C++

I've seen a number of different approaches to implementing a FSM.

Switch-case Function pointer tables object oriented programming

My question is what are the main factors I should be aware of when choosing one implementation over the other. In my case I only have 4 states with at most 2 transitions at each state. My main goal is for the implementation to be easily readable for someone else to modify.

Thanks

Upvotes: 1

Views: 1592

Answers (1)

hutorny
hutorny

Reputation: 873

Please take a look at method-based FSA implementation

// abstract FSA
template<class C, typename T>
struct fsa {
    struct state_t {
        typedef state_t (C::*type)(T);
        inline state_t(type f) : state(f) {}
        type state;
    };

    fsa(state_t init) : state(init) {}

    inline bool next(T val) {
        state = (static_cast<C*>(this)->*state.state)(val);
        return state.state != nullptr;
    }
private:
    state_t state;
};

//concrete FSA implementation
struct myfsa : fsa<myfsa,char> {
    inline myfsa() : fsa<myfsa, char>(&myfsa::start) {}
    state_t start(char) {
        std::cout << "start" << std::endl;
        return &myfsa::state1;
    }
    state_t state1(char) {
        std::cout << "state1" << std::endl;
        return &myfsa::state2;
    }
    state_t state2(char) {
        std::cout << "state2" << std::endl;
        return nullptr;
    }
    char get() { return ' '; /*TODO*/ }
    void run() {
        while(next(get()));
    }
};

Upvotes: 1

Related Questions