user2553780
user2553780

Reputation: 151

Static member object initialization

I'm trying to implement a template for states machines in C++, but I'm not sure how to handle static object members. Each state machine would be defined by its state variables and its transitions (which are structs). For instance:

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

Now, suppose I'm trying to implement the 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 ...
};

Ok. So each instance of foo_stm should have a different set of state variables, but all instances should use the same transitions. The question is, how should I define/declare stm<struct foo_stv> in order to use foo_transitions as its class level transitions member?

Also any advice about C++ coding customs is welcome, since I come from the C coding world and just getting started with some C++ mechanics.

EDIT: Just to make clear my question, I guess you should forget about the stm logic and focus on the following: What's the correct way of doing something like...

foo_stm::stm.transitions = foo_transitions;

Upvotes: 1

Views: 635

Answers (1)

BartoszKP
BartoszKP

Reputation: 35911

All right, I think that what you want to do is:

template <class T>
class stm
{
  T *stv;
  static transition<T> *transitions;
};

template<class T>
transition<T>* stm<T>::transitions; //define static template member

And then:

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

Upvotes: 2

Related Questions