Initialization of struct containing anonymous union

Carl Sturtivant via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Aug 14 07:57:49 PDT 2017


On Monday, 14 August 2017 at 14:49:57 UTC, Steven Schveighoffer 
wrote:
> On 8/14/17 10:36 AM, Carl Sturtivant wrote:
>> On Monday, 14 August 2017 at 14:24:40 UTC, Steven 
>> Schveighoffer wrote:
>>>
>>> I think what the docs mean is that as soon as an anonymous 
>>> union is present, you can't initialize anything further than 
>>> the first union field.
>> 
>> I understood that, hence my remark that "this is not helpful".
>
> OK. I thought you meant that the documentation is not helpful 
> enough to understand what it means.
>
>> 
>>>> So it seems I am forced to assign explicitly to each member 
>>>> of the struct, an ugly process.
>>>>
>>>> What is a nice way to solve this problem?
>>>
>>> I think the only way to solve it is with a constructor:
>>>
>>> this(int ival, double xval) { i = ival; x = xval; }
>> 
>> As I though I made clear, I don't want write assignments to 
>> each variable in a 50 or 100 member struct from a library when 
>> D could supply a better solution.
>
> Sorry, I thought you meant to assign the fields manually 
> outside an initializer function.
>
>> I can print out such a struct using writeln, but can find no 
>> way to use that text cleaned up in source code to create such 
>> a struct. Is D completely deficient here?
>
> Hm... have you tried named field initializers?
>
> mess m = { i: 99, x: 3.14};
>

I could do that, but again it would involve finding the 50 or 100 
names and writing text that looks quite like the text of an 
assignment except using colon instead of equals. So just as long 
and ugly.

>
> I believe you could generate a constructor given the 
> introspection of the fields themselves. Probably would be messy 
> though.

Probably worth investigating, though not handy when quickly 
writing a short one-off tool. Was hoping D would have a better 
way.




More information about the Digitalmars-d-learn mailing list