简体   繁体   中英

a struct to hold template specialization parameters

I have an internal implementation of a StateMachine, one that works on a set of parameters:

struct StateMachine {
  enum State { S1, S2, S3 };
  enum Events { E1, E2, E3 };

  State current_state_;
  Data data_;
  State Process(Events event);
};

Which works reasonably well. Now, I'd like to template parametrize it so that it can be reused, something like:

template<typename StateT, typename EventT, typename DataT>
struct StateMachine {
  StateT current_state_;
  DataT data_;
  StateT Process(EventT event);
};

Because the actual example is more concrete, I end up having many many template arguments. What I'd like is to be able to pass 1 concrete substructure defining these template specializations, so:

template<typename ContainerT>
struct StateMachine {
  ContainerT::StateT current_state_;
  ContainerT::DataT data_;
  ContainerT::StateT Process(ContainerT::EventT event);
};

And then I can have multiple containers defined in my project:

struct SM1 {
  typedef enum { S4, S6, S8, ... } StateT;
  typedef enum { E4, E8, E16, ... } EnumT;
  typedef SM1 DataT;

  string payload_data;
};
StateMachine<SM1> sm1;

struct SM2 {
  typedef enum { S3, S6, S9, ... } StateT;
  typedef enum { E3, E6, E9, ... } EnumT;
  typedef SM2 DataT;

  uint32 payload;
};
StateMachine<SM2> sm1;

Is this a proper way to go about? Or is there a better pattern for this kind of access ?

Yep, that is a valid approach to pack template parameters into a structure.

To access those from a template typename prefix is required, eg typename ContainerT::StateT .

typedef enum { S4, S6, S8, ... } StateT is a C-style declaration, in C++ do enum StateT { S4, S6, S8, ... } .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM