Nested Structs (Solution)

js.mdnq js_adddot+mdng at gmail.com
Thu Dec 13 00:55:43 PST 2012


On Thursday, 13 December 2012 at 01:57:26 UTC, d coder wrote:
>> The name doesn't matter. I just wanted to annoy Walter again 
>> with yet
>>> another bit of evidence that completeness of a feature is 
>>> important even if
>>> it doesn't seem to have an obvious use case. People will do 
>>> what is logical
>>> and end up with hacks like that.
>>>
>>
> I believe it *is* an obvious use case. In D we use structs when 
> we want to
> save on memory. And creating a class environment to encapsulate 
> a system of
> structs is an obvious use case. In fact I am in this situation 
> and thanks
> to your hack, I will try to use it for the time being.
>
>
>>
>>>  Little would have to be done to the structs to make it work. 
>>> In fact,
>>>> the method should work if D ever decides to support such a 
>>>> feature with
>>>> little change. Compile times could be increased though by 
>>>> removing the
>>>> templating, but unfortunately that might require a lot of 
>>>> work. A mixin
>>>> might simplify it.
>>>>
>>>
>> Ok, maybe thats why my posts have not received any attention 
>> except by you
>> ;)
>
>
> Let us trend it ;-)
>
> Regards
> - Puneet

I've created some mixins that make life a little easier:

http://dpaste.dzfl.pl/64025e0a

It makes it easier to refactor/rename.

mixin(StructNestType!("B", "_A!(", "_NestLevel", "b1"));

note the weird syntax of the class "_A!(", this is to allow when 
A has more than one template parameter.

Note that if you might want to create your constructors only for 
_NestLevel = true. e.g., use a static if. This way you don't have 
lame casting issues trying to cast one struct to another because 
they differ on the _NestLevel.

The opAssign is used to copy one type to another. One can only 
make assignments from objects of the same parent type. (else the 
parent will be wrong)

Using alias this will help avoid other problems. (which is sort 
of the point) These nested structs are meant to wrap values to 
add encapsulated functionality. As far as the outside world is 
concerned they are suppose to be just normal values, with, 
potentially, some additional functionality.

I believe that the code is now usable in that it accomplishes the 
task(zero overhead and small performance hit) and can be 
refactored somewhat easily. The syntax is far from pretty but if 
D ever gets such a feature it shouldn't be too hard to update the 
code(for large projects, one could make a simple regex parser for 
it to update everything).

It would be nice if D implements such a feature because it will 
look more natural.


More information about the Digitalmars-d mailing list