union initalization
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Jul 21 19:08:06 PDT 2016
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
> 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
More information about the Digitalmars-d-learn
mailing list