union c++

Started by
5 comments, last by aboeing 19 years, 11 months ago
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.
Advertisement
The only way is with accessors AFAIK.
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
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]
Check out Boost.Any.
--God has paid us the intolerable compliment of loving us, in the deepest, most tragic, most inexorable sense.- C.S. Lewis
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!
boost::variant ownz0rs boost::any

This topic is closed to new replies.

Advertisement