Here is a simplified version of the code I am trying to write:
template<typename Derived>
class StateMachine
{
public:
void SetState(Derived::State s) {
static_cast<Derived*>(this)->TransitionTo(s);
}
};
class MyFSM : public StateMachine<MyFSM>
{
public:
enum class State {
State1,
State2,
State3
};
void TransitionTo(State s) {
_state = s;
}
private:
State _state = State::State1;
};
I'm using c++11 with clang. The error I get here is 10:17: error: missing 'typename' prior to dependent type name 'Derived::State'
for the declaration of SetState
. I've also tried adding typename Derived::State DerivedState;
and then using DerivedState
instead of Derived::State
, but then I get error: unknown type name 'DerivedState'
.
More confusing still, I tried typedef typename Derived::State DerivedState;
and then I get the error: error: no type named 'State' in 'MyFSM'
. my last try was typedef enum class Derived::State DerivedState;
and then I get the most confusing error of all: error: no enum named 'State' in 'MyFSM'
.
I'm out of my depth with templates here and would welcome any help understanding this! Also, there may be a better pattern to use here. The main thing I'm going for is that the StateMachine
class has some common functionality and then there are a bunch of different state machines, each with their own state and transition function. I have another way of doing it that requires passing in this
to SetState
(when called from within MyFSM
, which is a simplified version of what I'm doing), but that's ugly for it's own reason. I'd love to avoid this tempalted class thing, but my main goal is making the derived classes as easy to write and understand as possible.