Archived

This topic is now archived and is closed to further replies.

union c++

This topic is 4953 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Is there any way to know which member of a union was last ''set''? Or at least some way to transparently emulate this? eg:
typedef union {
int i;
float f;
bool IsInt();
} bla;

//code:

bla.i=5;
if (bla.IsInt()) //this would return true...

sorry if its not really clear... thanks.

Share this post


Link to post
Share on other sites
No, you would need to use accessors like this. Unfortunately this might not be acceptable for you if memory constraints is the reason why you are using a union, as it adds a bool to the size. Note there's no initialization in my example, so the state is invalid until you set a value.


class MyUnion
{
public:
float F() {return mF;}
int I() {return mI;}
void F(float Value){mF=Value;mIsInt=false;}
void I(int Value){mI=Value;mIsInt=true;}
bool IsInt(){return mIsInt;}
bool IsFloat(){return !mIsInt;}
private:
union
{
int mI;
float mF;
};
bool mIsInt;
};


Edit: I should learn to check my post before pressing the post buttons. It missed the return types, and F and I returned the wrong values...

[edited by - fredizzimo on May 20, 2004 9:29:10 AM]

Share this post


Link to post
Share on other sites