简体   繁体   中英

How to define a generic data type containing enums in C?

I am trying to define a generic macro in c which does a state transition in a state machine and "logs" some data on the state transition (reason of the transition and the number of transitions done).

As this approach shall be used in multiple state machines i want to use a generic macro like:

#define STATE_TRANSITION(state_variable, new_state, reason)  /
    state_variable.state = new_state;   /          /* new_state is an enum value */
    state_variable.transition_reason = reason; /   /* reason is an enum value */
    state_variable.state_transition_counter++;     /* the counter may overflow */

To make this possible i am thinking of a state type like this

struct specific_state {
    enum POSSIBLE_STATES state;
    enum STATE_TRANSITION_REASONS transition_reason;
    uint8 state_transition_counter;
}

which can be used for a specific state machine.

To make sure that every state uses the same structure (to make the macro work) i try to use some parent type for a state. My problem is that enum POSSIBLE_STATES and enum STATE_TRANSITION_REASONS can vary for the different statemachines. But the only generic member in my struct would be state_transition_counter :)

My question is now:

Is there a possibility to define a type in c which represents a base "class" like:

struct debuggable_state {
    enum state;
    enum transition_reason;
    uint8 state_transition_counter;
}

which can be subclassed afterwards (to apply the specific enum types)?

Perhaps i will replace the macro by an inline function to make it type safe, but i am still not sure if my approach is possible at all.

您可以使用int代替泛型结构中的枚举,无论如何枚举都表示为int。

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