gpt4 book ai didi

c++ - 静态成员对象初始化

转载 作者:行者123 更新时间:2023-11-30 04:15:06 24 4
gpt4 key购买 nike

我正在尝试用 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作为类(class)水平transitions成员(member)?

也欢迎任何关于 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++ - 静态成员对象初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18563160/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com