Array start index
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Feb 7 12:28:30 PST 2017
On 02/07/2017 02:11 AM, Bastiaan Veelo wrote:
> void init() {
> 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;
> }
You forgot to call that most important function. ;)
1) I don't understand the first assert there, which does not pass for
me, so I commented it out.
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;
}
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;
Ali
More information about the Digitalmars-d-learn
mailing list