Collections question
default0 via Digitalmars-d
digitalmars-d at puremagic.com
Sat Nov 28 00:54:02 PST 2015
On Friday, 27 November 2015 at 20:14:21 UTC, Andrei Alexandrescu
wrote:
> There's this oddity of built-in hash tables: a reference to a
> non-empty hash table can be copied and then both references
> refer to the same hash table object. However, if the hash table
> is null, copying the reference won't track the same object
> later on.
>
> Fast-forward to general collections. If we want to support
> things like reference containers, clearly that oddity must be
> addressed. There are two typical approaches:
>
> 1. Factory function:
>
> struct MyCollection(T)
> {
> static MyCollection make(U...)(auto ref U args);
> ...
> }
>
> So then client code is:
>
> auto c1 = MyCollection!(int).make(1, 2, 3);
> auto c2 = MyCollection!(int).make();
> auto c3 = c2; // refers to the same collection as c2
>
> 2. The opCall trick:
>
> struct MyCollection(T)
> {
> static MyCollection opCall(U...)(auto ref U args);
> ...
> }
>
> with the client code:
>
> auto c1 = MyCollection!(int)(1, 2, 3);
> auto c2 = MyCollection!(int)();
> auto c3 = c2; // refers to the same collection as c2
>
> There's some experience in various libraries with both
> approaches. Which would you prefer?
>
>
> Andrei
This is probably naive and silly, but: can't you just put a dummy
element in the hash table on creation of the struct, set a flag
"containsDummyElement" and then have all methods you implement
from that struct (count, range implementation, etc) check that
flag and ignore the one element it contains when the flag is set?
Then when the first real element gets added, just remove the
element and reset the flag. When the last element gets removed,
put the dummy element back.
I feel like I'm either misunderstanding the problem or
misunderstanding built-in associative arrays, so sorry if what I
said above is really stupid and cannot (or should not) be done
for reasons everyone else here knows about.
More information about the Digitalmars-d
mailing list