基于类的状态机?
在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
成员函数模板的定义应该是这样的:
也就是说,它应该是简单的
setState
,而不是setState
。后一种语法用于函数模板专门化。由于T
是类型参数,因此特化将被视为函数部分模板特化,这是不允许的。The definition of the member function template should be this:
That is, it should be simply
setState
instead ofsetState<T>
. The latter syntax is used in function template specialization. SinceT
is a type parameter, the specialization would be considered as function partial template specialization which is not allowed.没有详细信息很难说,但是您可以创建一个基本
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.
避免模板的另一个选项是为您的游戏状态定义一个纯虚拟基类,然后将对不同游戏状态的引用传递给您的函数。例如,
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,