Initialization of struct containing anonymous union

Carl Sturtivant via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Aug 14 08:24:31 PDT 2017


On Monday, 14 August 2017 at 15:11:35 UTC, Steven Schveighoffer 
wrote:
> On 8/14/17 10:57 AM, Carl Sturtivant wrote:
>> 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.
>
> Well, you only have to initialize the ones that aren't 
> defaulted. So in some use cases, this is hugely beneficial.
>
> But it seems in your case, you want to intialize everything 
> explicitly (but only one member from each union).
>
> Tried this, also works. Looks like you just have to name items 
> after the unions (i.e. when you are skipping members). Ugly, 
> but passable:
>
> struct mess
> {
>     union
>     {
>         int i;
>         string s;
>     }
>     double x;
>     int z;
> }
>
> mess s = {99, x: 3.14, 5};
>
> -Steve

!
Agreed!


More information about the Digitalmars-d-learn mailing list