静态成员对象初始化

Static member object initialization

本文关键字:初始化 成员对象 静态      更新时间:2023-10-16

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

好吧,我想你想做的是:

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 ...
};