Struct member with variable data type

I have a structure I am creating that has one data member (Parameter) that is an enumerated value. There are fifteen possible values in the Parameter enumeration type.

The value of Parameter determines the value and type of a second data member (value).

struct myData
{
myEnumeratedType Parameter;
?? Value;
};

Possible types of Value:

ParameterType00
{
Unsigned 1
Padding
}

ParameterType01
{
Unsigned 4
Padding
}

ParameterType02
{
EnumeratedType2
Padding
}

You get the picture; there are fifteen potential types for Value based on the value of data member parameter.

My question: What is the best way to define this type of structure. Obviously, I'll use a "struct"; but what is the best way to define the fifteen potential different types? Is a union the best method or is there another way?


struct myStructure
{
integer headerItem1
float headerItem2
myEnumeratedType Parameter
union parameterValueType
{
ParameterType00 parameterValue00
ParameterType01 parameterValue01
ParameterType02 parameterValue02
.
.
.
ParameterType15 parameterValue15
}parameterValue
}
A lot depends on how you're going to use myStructure.

A union is the simplest approach, but does not protect you from misusing the enum/union value pairs, which are public by default in a struct.

I would make a class to hold just the enum/union pair and make them private. That gives more control over access to the pair.

1
2
3
4
5
6
7
8
class MyEnumValuePair
{   myEnumeratedType Parameter
    union parameterValueType parameterValue;
public: 
  // Constructors
  // getters
  // setters
};


PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.
Last edited on
Thank you. I will be sure to use code tags next time. It's always nice to get a second opinion.
Topic archived. No new replies allowed.