Jump to content
  • Advertisement

Archived

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

aboeing

union c++

This topic is 5146 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
Advertisement
Polymorphism is generally a better way of implementing in C++ what you would do in C with unions; it''s safer and provides more functionality.

Mark

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
Thanks for the suggestions guys, I think I will use fredizzimo''s approach over the any''s as its most-close to a union, so I have to change less code
Thanks!

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
boost::variant ownz0rs boost::any

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!