Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling different datatypes in a single structure

Tags:

c++

I need to send some information on a VxWorks message queue. The information to be sent is decided at runtime and may be of different data types. I am using a structure for this -

struct structData
{
  char m_chType;    // variable to indicate the data type - long, float or string
  long m_lData;     // variable to hold long value
  float m_fData;    // variable to hold float value
  string m_strData; // variable to hold string value
};

I am currently sending an array of structData over the message queue.

structData arrStruct[MAX_SIZE];

The problem here is that only one variable in the structure is useful at a time, the other two are useless. The message queue is therefore unneccessarily overloaded. I can't use unions because the datatype and the value are required. I tried using templates, but it doesn't solve the problem.I can only send an array of structures of one datatype at a time.

template <typename T>
struct structData
{
  char m_chType;
  T m_Data;
}

structData<int> arrStruct[MAX_SIZE];

Is there a standard way to hold such information?

like image 922
psvaibhav Avatar asked Nov 29 '22 20:11

psvaibhav


2 Answers

I don't see why you cannot use a union. This is the standard way:

struct structData
{
  char m_chType;    // variable to indicate the data type - long, float or string
  union
  {
    long m_lData;         // variable to hold long value
    float m_fData;    // variable to hold float value
    char *m_strData; // variable to hold string value
  }
};

Normally then, you switch on the data type, and then access on the field which is valid for that type.

Note that you cannot put a string into a union, because the string type is a non-POD type. I have changed it to use a pointer, which could be a C zero-terminated string. You must then consider the possibility of allocating and deleting the string data as necessary.

like image 189
1800 INFORMATION Avatar answered Dec 10 '22 14:12

1800 INFORMATION


You can use boost::variant for this.

like image 34
Ylisar Avatar answered Dec 10 '22 16:12

Ylisar