我正在尝试用C ++实现状态机的模板,但我不确定如何处理静态对象成员。每个状态机将由其状态变量及其转换(结构)定义。例如:
// stm.h
template <class T>
struct transition
{
... transition relevant data depending on state variables T ...
};
template <class T>
class stm
{
T *stv; // state variables
static struct transition<T> *transitions; // I would like to have only one copy of transitions for stm's of type T
... etc ...
};
现在,假设我正在尝试实现stm foo:
// foo_defs.h
struct foo_stv
{
char a;
int b;
};
// foo_transitions.h
// Note that I'm using a different file to keep everything in order
#include "stm.h"
#include "foo_defs.h"
struct transition<struct foo_stv> foo_transitions[] =
{
{ ... trans1 ... },
...,
{ ... transN ... }
};
// foo_stm.h
#include "stm.h"
#include "foo_defs.h"
#include "foo_transitions.h"
class foo_stm
{
stm<struct foo_stv> stm;
struct foo_stv stv;
... other data ...
};
确定。因此foo_stm的每个实例都应该有一组不同的状态变量,但是所有实例都应该使用相同的转换。问题是,我应该如何定义/声明stm<struct foo_stv>
才能将foo_transitions
用作其级别transitions
成员?
另外,关于C ++编码习惯的任何建议都是受欢迎的,因为我来自C编码世界并且刚刚开始使用一些C ++技术。
编辑:为了明确我的问题,我想你应该忘记stm逻辑并专注于以下内容:做正确事情的正确方法是什么......
foo_stm::stm.transitions = foo_transitions;
答案 0 :(得分:2)
好吧,我认为你想要做的是:
template <class T>
class stm
{
T *stv;
static transition<T> *transitions;
};
template<class T>
transition<T>* stm<T>::transitions; //define static template member
然后:
//define static member for particular template instantiation
template<>
transition<foo_stv>* stm<foo_stv>::transitions = foo_transitions;
class foo_stm
{
stm<struct foo_stv> stm;
struct foo_stv stv;
... other data ...
};