union initalization
Rufus Smith via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Jul 21 20:00:20 PDT 2016
On Friday, 22 July 2016 at 02:08:06 UTC, Ali Çehreli wrote:
> On 07/21/2016 06:48 PM, Rufus Smith wrote:
> > I would like to combine two types
> >
> >
> > template Foo(A, B = 4)
> > {
> > union
> > {
> > byte b = B;
> > int a = A << 8;
> > }
> > }
> >
> > This packs a and b together in to an int bytes, saving an
> int(rather
> > than storing a and b in an int each) and makes it easier to
> access.
>
> Bitfields may actually be useful in this case:
>
> https://dlang.org/phobos/std_bitmanip.html#.bitfields
>
They don't allow default assignment though?
> > I get an error about overlapping default initialization. They
> don't
> > actually overlap in this case because of the shift.
>
> The following at least compiles:
>
> struct Foo(int A, byte B = 4)
> {
> union
> {
> byte b = void;
> int a = void;
> uint __both = (A << 8) | B;
> }
> }
>
> void main() {
> auto f = Foo!(42)();
> }
>
> Ali
Maybe... I don't like extra member. Bitfields seem like it would
be the best way but I require default initialization. I want to
hide as details of the work on unpacking as possible.
More information about the Digitalmars-d-learn
mailing list