Array start index
Bastiaan Veelo via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Feb 7 13:25:50 PST 2017
On Tuesday, 7 February 2017 at 20:28:30 UTC, Ali Çehreli wrote:
> You forgot to call that most important function. ;)
Hah of course. I assumed the name would give it some special
meaning, like postblit.
> 1) I don't understand the first assert there, which does not
> pass for me, so I commented it out.
The intention is to check that (_payload.ptr - first) is larger
than 0.
> 2) May bad: init() is not a good name for a struct member, so
> it should be renamed:
>
> void initialize() {
> // assert( first < cast(size_t)_payload.ptr);
> // Address space underrun.
> assert(-first < size_t.max - cast(size_t)_payload.ptr);
> // Address space overrun.
> this._ptr = _payload.ptr - first;
> }
>
> 3) Instead of having to remember to call it, let's introduce a
> function that does it for us:
>
> auto makeStaticArray(T, ptrdiff_t first, ptrdiff_t last)() {
> auto s = StaticArray!(T, first, last)();
> s.initialize();
> return s;
> }
OK good.
> unittest {
> // StaticArray!(int, -10, 10) arr;
> auto arr = makeStaticArray!(int, -10, 10);
>
> > foreach (i, ref e; arr)
> > e = i;
>
> Unrelated: That line passes because you're building 32-bits.
> Here is the error I got:
>
> Error: cannot implicitly convert expression (i) of type long
> to int
>
> You can cast it:
>
> e = cast(int)i;
>
> or by
>
> import std.conv : to;
> e = i.to!int;
Thanks a lot for your illustrative answers, including the next
one!
Bastiaan.
More information about the Digitalmars-d-learn
mailing list