union initalization
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Jul 21 23:21:30 PDT 2016
On 07/21/2016 08:00 PM, Rufus Smith wrote:
>> Bitfields may actually be useful in this case:
>>
>> https://dlang.org/phobos/std_bitmanip.html#.bitfields
>>
>
> They don't allow default assignment though?
A factory function can help:
import std.bitmanip;
struct S(int a_init, byte b_init) {
mixin (bitfields!(int, "a", 24,
byte, "b", 8));
@disable this();
}
auto makeS(int a_init, byte b_init = 4)() {
auto s = S!(a_init, b_init).init;
s.a = a_init;
s.b = b_init;
return s;
}
void main() {
const s = makeS!42();
assert(s.a == 42);
assert(s.b == 4);
}
>> 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.
Me neither. Besides, 'b' coincides with a different part of 'a'
depending on the endianness of the system.
Ali
More information about the Digitalmars-d-learn
mailing list