vendredi 24 novembre 2017

Use of union in a command data structure

I am working on a project in which we pass commands to lower layer from upper layer.

1. Handle Single command at a time

we use following data structure.

struct Command{
     //Different command types==> SEND / CREATE_TRANSACTION etc.
     CommandType type;

     //Associated parameters with every command
     union{
         struct{
             string remote_ip;
             uint16_t remote_port;
         }address;

         struct{
             string transaction_id;
             string transaction_details;
         }tsx;
         .
         .
         .
     }params;
};

We pass different parameters for different commands. Union makes it memory efficient.

Is there any better way (or a design pattern) to do it in C++?

Another one.

2. Handle multiple commands in a single command object.

I can do it in this way:

struct Command{
    uint64_t flag; //ORed value of different command types 

    //parameters
    struct{
        string remote_ip;
        uint16_t remote_port;
    }address;

    struct{
        string transaction_id;
        string transaction details;
    }tsx;
};

But, it is not memory efficient.

Is there any better way to create multiple commands in a single object (in C++)?

Aucun commentaire:

Enregistrer un commentaire