Collections question
Steven Schveighoffer via Digitalmars-d
digitalmars-d at puremagic.com
Mon Nov 30 08:06:55 PST 2015
On 11/27/15 3:14 PM, 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?
How do you prevent the AA behavior? In other words, what happens here:
MyCollection!(int) c1;
auto c2 = c1;
c1 ~= 1;
assert(c2.contains(1)); // pass? fail?
BTW, I third Jonathan's and Timon's suggestion -- go with an external
factory function. Use IFTI to its fullest!
-Steve
More information about the Digitalmars-d
mailing list