Quote:Original post by Shannon Barber
It's very difficult to make generic state-machine code.
Ok, I'm glad that it's not just me then :)
Quote:I wouldn't want the virtual call overhead here, which is the same thing as a member function pointer dereference.
I see now that one of the assumptions I'm making in my design is that there won't be an overabundance of states, and that state transitions wouldn't be common enough to cause any kind of cpu/mem hit. But you're right - it isn't ideal. Then again, if you've just got a huge case statement then you've got the overhead of a huge jump table also. And I figured that encapsulating the member function pointers into a discreet chunk of ram would be much more cache-friendly than having a massive vtable? Does that make sense or is my head full of FUD?
Quote:If you stay on this track, I would just go fully OOP and make an interface for IState & IStateMachine:
The problem with this approach is that the classes that implement IState are not "part" of any other class. Which makes it very difficult to use the state machine to control any kind of private process that you don't necessarily want to expose via public members and accessors/mutators. There are OO ways around that limitation, but at that point you've just caused a considerable amount of bloat and complication without really gaining anything it seems.
Quote:If you wanted to get serious about re-usable state-machine code in C++, I'd look into a policy base meta-template implementation either using Loki or boost::mpl.
I like the idea of using policies to define behavior for transitions, handling null states, etc. But I'm not yet to the point in the design where I'm ready to think about maximizing reusability. I just want it to be reasonable at this point, not perfect.
Again, meta-templates could possibly present a very run-time efficient implementation, but complications include:
1) Executable bloat that could possibly ruin cache performance and defeat the purpose of avoiding method pointers/vtable.
2) The cost of integrating a state machine for aggregation or inheritence by any class could include a LOT of really ugly code. I use macros in my example, but it would be totally reasonable to not use them - the code would still be readable. Meta-template setups for a state machine could get very complex and impossible to debug IMO.
In general, the meta-template approach is fun but ultimately a pain to debug and often ends up offloading a bunch of complexity onto the client classes, which in turn increases chances for bugs to creep in. I also wouldn't expect meta-templates to be very friendly with the SNSystems compiler for PS2 etc.
Quote:The more common approach today is to use a tool that generates C or C++ code.
Could you give me some pointers on where to find tools like this? Or is it mostly a homebrew kind of thing?
Thanks!