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:
Make all strutures to inherit from a same base interface and use smart pointers.
Use
union
s (old-style)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