基于类的状态机?

发布于 2024-12-02 22:38:15 字数 468 浏览 5 评论 0原文

在 C++ 中,我试图为游戏制作一个基于类的简单状态机。

stateMan.setState<mainMenuState>();

我有一个类,其声明为:

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

测试代码为:

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

显然这不起作用,因为 函数模板部分特化 'setState'不允许。

除了非面向对象之外,还有更好的方法吗?

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 function template partial specialization ‘setState<T>’ is not allowed.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

终止放荡 2024-12-09 22:38:15

成员函数模板的定义应该是这样的:

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

也就是说,它应该是简单的setState,而不是setState。后一种语法用于函数模板专门化。由于 T 是类型参数,因此特化将被视为函数部分模板特化,这是不允许的。

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.

一曲琵琶半遮面シ 2024-12-09 22:38:15

没有详细信息很难说,但是您可以创建一个基本 State 类,并从它继承不同的状态。

如果您仍然想为此使用类,您可以看到一个有趣的
使用 boost.mpl 的示例

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.

铁憨憨 2024-12-09 22:38:15

避免模​​板的另一个选项是为您的游戏状态定义一个纯虚拟基类,然后将对不同游戏状态的引用传递给您的函数。例如,

//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); 
};

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); 
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文