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.
union c++
Is there any way to know which member of a union was last ''set''?
Or at least some way to transparently emulate this?
eg:
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
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.
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]
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]
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement