1

我正在尝试在 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;
4

1 回答 1

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 ...
};
于 2013-09-03T11:58:23.473 回答