Collections question

Andrei Alexandrescu via Digitalmars-d digitalmars-d at
Fri Nov 27 12:14:24 PST 2015

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?


More information about the Digitalmars-d mailing list