I am looking for a simple and elegant way of organizing containers in C. Most problems arise due to the inability to get the RTI. So, for example, suppose that there is a universal structure that stores data for QUEUE and STACK . It is clear that both such structures support PUSH and POP operations. But they are implemented in them in different ways.

Attention, a question: how to leave the general interface, but to avoid code duplication? Insert the switch...case inside the PUSH and POP also do not want.

    2 answers 2

    You can organize something like polymorphism:

     struct SequenceContainer { union { struct Stack stack; struct Queue queue; } container; void (*init)(struct SequenceContainer *hcontainer); void (*push)(struct SequenceContainer *hcontainer, const SequenceContainer_etype *elem); }; struct SequenceContainer *create_queue(void) { struct SequenceContainer *p = malloc(sizeof(struct SequenceContainer)); if (p != NULL) { p->init = queue_init; p->push = queue_push; p->init(p); } return p; } 

    Only it is necessary to closely monitor the use of this container - the possibilities of C in the diagnosis of type mismatch are limited. Therefore, C ++ is more suitable for such constructions.

      Try a different approach.

      Insert the structure that implements the container directly into the user data structure. This is conveniently due to the fact that the same user data can be simultaneously placed in different containers.

      For example, you can look at the hash table and doubly linked list (based on the Linux cyclic list include / linux / list.h )