开发者

A class-based state machine?

In C++ I'm trying to make a simple state machine for a game, based on classes.

stateMan.setState<mainMenuState>();

I have a class with the declaration as:

class stateManager
{
  ...
  template <class T>
  void setState(void);
}

And the test code as:

template <class T>
void stateManager::setState<T>(void)
{
  T* blah = new T;
  delete blah;
}

And obviously this doesn't work since funct开发者_如何学Pythonion template partial specialization ‘setState<T>’ is not allowed.

Would there be a better way to do this besides doing it non-OO?


The definition of the member function template should be this:

template <class T>
void stateManager::setState(void)
{
   //...
}

That is, it should be simply setState instead of setState<T>. The latter syntax is used in function template specialization. Since T is a type parameter, the specialization would be considered as function partial template specialization which is not allowed.


Hard to say without the details, but you could do a base State class, and the different states inherit from it.

If you still want to use classes for this, you can see an interesting example using boost.mpl.


Another option that avoids templates would be to define a pure virtual base class for your game states, and then pass references to different game-states to your function. For instance,

//pure virtual base class that will define the state interfaces
class base_state { /*...*/ }; 

//a derived state class
class mainMenuState : public base_state { /*...*/ }; 

class stateManager
{
    //...

    //you can pass any derived base_state to this function
    void setState(base_state* state); 
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜