0

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?

Chris
  • 26,361
  • 5
  • 21
  • 42
inigmati
  • 23
  • 3
  • See [Heterogeneous containers in C++](https://stackoverflow.com/questions/7804955/heterogeneous-containers-in-c) – Jason Sep 14 '22 at 15:25
  • ok, what do you want to do with them afterwards? do you just want to keep them alive, do you have a common interface (is it via a common base or concept), how do you plan to manipulate them? – lorro Sep 14 '22 at 15:30

2 Answers2

2

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;
}
Chris
  • 26,361
  • 5
  • 21
  • 42
1

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

Chris
  • 26,361
  • 5
  • 21
  • 42
Adrian Maire
  • 14,354
  • 9
  • 45
  • 85