Home > Net >  I want to push multiple structs in single queue in C
I want to push multiple structs in single queue in C

Time:09-15

I have two types of events with associated values such as:

struct EventRequest
{
    char EventType;
    int RetryCount;
} ER;

struct EventStatus
{
    char EventType;
    char StatusType;
    short RetryCount;
} ES;

I want to push the above structs onto one single queue/stack such as:

queue<typedef>q;

q.push(ER);
q.push(ES);
q.push(ER):
.
.
.

How can I do that?

CodePudding user response:

One solution to this would be polymorphism: both structs inheriting from a common base class. However, that implies an "is-a" relationship that may not exist and would make your code awkward and harder to understand. With that in mind, another solution to this (since C 17) would be std::variant.

#include <queue>
#include <variant>

struct EventRequest {
  char EventType;
  int RetryCount;
} ER;

struct EventStatus {
  char EventType;
  char StatusType;
  short RetryCount;
} ES;

int main() {
  std::queue<std::variant<EventRequest, EventStatus>> q;

  q.push(ER);
  q.push(ES);

  return 0;
}

CodePudding user response:

There are several solution to that problem:

  1. Make all strutures to inherit from a same base interface and use smart pointers.

  2. Use unions (old-style)

  3. For this example, I am going to show how to use std::variant

#include <variant>
#include <queue>

struct EventRequest
{
    char EventType;
    int RetryCount;
};

struct EventStatus
{
    char EventType;
    char StatusType;
    short RetryCount;
};

using AnyEvent = std::variant<EventRequest, EventStatus>;

int main()
{
    std::queue<AnyEvent> event;
    
    event.push(EventRequest());
    event.push(EventStatus());

    return 0;
}

Run this code here: https://onlinegdb.com/D17aVXA1K

  •  Tags:  
  • c
  • Related