Re: Anonymous union rules against constructors & assignment
I've found a hack that works in MS VS 2005.
Unfortunately, it's uses non-standard C++ (anonymous struct), but hey, it
works.
This hack enables unlimited pseudo members occupying zero overhead.
#include <iostream>
struct Data
{ int data[2];
void Init(int a=0,int b=0) { data[0]=a; data[1]=b; }
static Data New(int a=0,int b=0) { Data d; d.Init(a,b); return d; }
};
template <int ITEM>
class Item: Data
{
public:
operator int() const { return data[ITEM]; }
Item& operator=(int i) { data[ITEM]=i; return *this; }
Item& operator=(const Item& item) { data[ITEM]=item.data[ITEM]; return
*this; }
};
class Twin
{
public:
union
{ Data twin;
struct { Item<0> d0; };
struct { Item<1> d1; };
};
Twin():twin(Data::New()) { }
Twin(int a,int b):twin(Data::New(a,b)) { }
Twin& operator=(const Twin& t) { twin=t.twin; return *this; }
};
int main()
{ Twin u(123,456),v(7,8);
printf("u.d0=%d, u.d1=%d\n",(int)u.d0,(int)u.d1);
u.d0=v.d0; // u.d1 should be left unaffected
printf("u.d0=%d, u.d1=%d\n",(int)u.d0,(int)u.d1);
printf("sizeof(Twin)=%d, sizeof(Data)=%d\n",sizeof(Twin),sizeof(Data));
return 0;
}
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]