user997112
user997112

Reputation: 30625

One class representing multiple structs (with different members) safely

I receive input data which contains different message types. For each message I extract the relevant details to a general ReturnObject struct:

void processMessage(const std::byte& bytes, ReturnObject& obj)
{
    switch(msgType)
    {
        // Extract message type 1 fields
        // Extract message type 2 fields
        // etc
    }
} 

Lets say message 1 has these fields:

int a;
int b;
char c;
string d;

Message 2 has some overlap:

int a;
string d;
double e;
float f;

(There are about 20 different messages in total)

At the moment ReturnObject contains the superset of the fields:

struct ReturnObject
{
    int a;
    int b;
    char c;
    string d;
    double e;
    float f;
};

I'd like ReturnObject to be type-safe and represent one message at a time. When it represents message 1, only a, b, c and d are accessible. One instance will only represent one message type at a time.

What is the best way to achieve this in C++20?

Upvotes: 0

Views: 95

Answers (1)

Vlad Feinstein
Vlad Feinstein

Reputation: 11311

I would consider polymorphism. This looks like a factory pattern. Your processMessage could just return a pointer to an appropriate object. No need to control access as the irrelevant members simply are not present.

Upvotes: 0

Related Questions