Static indexing
Steven Schveighoffer
schveiguy at gmail.com
Wed Jan 12 16:04:59 UTC 2022
On 1/12/22 3:59 AM, JG wrote:
> Hi,
>
> I want to make a type which has two fields x and y but can
> also be indexed with [0] and [1] checked at compile time.
>
> Is the following reasonable / correct?
>
> struct Point
> {
> double x;
> double y;
> alias expand = typeof(this).tupleof;
> alias expand this;
> }
> unittest
> {
> Point p = Point(1.2,3.4);
> assert(p[0]==1.2);
> assert(p[1]==3.4);
> assert(!__traits(compiles,Point.init[3]));
> }
I was going to reply that you can't do it this way, but it works. Very
interesting!
I would say to go with that, and I love that technique! Seems like it
started allowing alias to `tupleof` in 2.094.
`std.typecons.Tuple` does it much differently. It declares the tuple as
an alias-this'd member, and then defines named accessors for each of the
items (if you give them names).
One thing I did find is that foreach doesn't like your mechanism,
whereas the Tuple mechanism does work:
```d
foreach(x, y; only(Point(1.0, 2.0)) {} // error
foreach(x, y; only(tuple(1.0, 2.0)) {} // ok
```
-Steve
More information about the Digitalmars-d-learn
mailing list