静态成员对象初始化
Static member object initialization
我正试图在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 ...
};
相关文章:
- 为什么在C++中首先初始化成员类
- 是否可以防止省略聚合初始化成员?
- 正在复制具有未初始化成员的结构
- C++:将初始化的对象传递给另一个类的构造函数;需要不必要的构造函数吗?
- 使用大括号或括号初始化成员变量
- C++结构:强制初始化成员?
- 具有空洞初始化的对象的生存期
- 如何在初始化列表中的构造函数之后初始化变量/对象?
- 分配给已删除/未初始化的对象
- C++中未初始化成员布尔变量的默认值是多少?
- 指向未由对象地址初始化的对象的指针如何将值分配给类的数据成员
- C 如何避免访问尚未初始化的对象的成员
- 使用从另一个类继承的类的对象初始化成员对象
- 如何避免需要在初始化列表中初始化成员对象
- 指针的数组要分类对象和初始化成员值
- C++如何初始化成员对象
- 在C++中,当我初始化类对象数组时,当我想通过构造函数初始化类成员时,我应该怎么做
- 如何使用子对象的成员初始化父对象
- 在初始化列表中初始化许多对象成员变量
- 为什么非初始化类对象指针可以访问指针成员,而结构指针不能访问指针变量