C++ unrestricted union workaround
- by Chris
#include <stdio.h>
struct B { int x,y; };
struct A : public B {
// This whines about "copy assignment operator not allowed in union"
//A& operator =(const A& a) { printf("A=A should do the exact same thing as A=B\n"); }
A& operator =(const B& b) { printf("A = B\n"); }
};
union U {
A a;
B b;
};
int main(int argc, const char* argv[]) {
U u1, u2;
u1.a = u2.b; // You can do this and it calls the operator =
u1.a = (B)u2.a; // This works too
u1.a = u2.a; // This calls the default assignment operator >:@
}
Is there any workaround to be able to do that last line u1.a = u2.a with the exact same syntax, but have it call the operator = (don't care if it's =(B&) or =(A&)) instead of just copying data? Or are unrestricted unions (not supported even in Visual Studio 2010) the only option?