Home > Net >  Read data from variant template used for queue
Read data from variant template used for queue

Time:09-20

Following code push two structs in one queue.

#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;
}

I am trying to read the front of the queue. How do I make a declaration which will return to the front of the queue?

?? = event.front();

How do I declare the question marked area?

CodePudding user response:

So if you are storing std::varient<EventRequest, EventStatus> in queue aliasing it AnyEvent you will get event.front(), AnyEvent as well.

So if you want to see which event you get, you can try something like this:

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

    AnyEvent s = event.front();
    try {
        EventRequest er = std::get<EventRequest>(s);
    }
    catch(std::bad_variant_access &exception){
        std::cout << exception.what() << std::endl;
        EventStatus es = std::get<EventStatus>(s);
    }
    return 0;
}

as if std::get<T>(variant) mismatch it will throw, std::bad_variant_access exception which you can use to change the type. Moreover std::get<Index> works with indexes if you want to access the type laying at particular index of your variant you can access that too.

CodePudding user response:

You should use std::visit as HolyBlackCat point out in comment.

    std::visit([](auto& e) { foo(e); }, event.front());
    std::visit([](auto& e) { foo(e); }, event.back());

https://godbolt.org/z/5anPsKsaK

  •  Tags:  
  • c
  • Related