Enum std.range.primitives.member isRandomAccessRange
Returns true if R is a random-access range. A random-access
range is a bidirectional range that also offers the primitive opIndex, OR an infinite forward range that offers opIndex. In
either case, the range must either offer length or be
infinite. The following code should compile for any random-access
range.
The semantics of a random-access range (not checkable during
compilation) are assumed to be the following (r is an object of
type R):
r.opIndex(n)returns a reference to thenth element in the range.
Although char[] and wchar[] (as well as their qualified
versions including string and wstring) are arrays, yields isRandomAccessRangefalse for them because they use
variable-length encodings (UTF-8 and UTF-16 respectively). These types
are bidirectional ranges only.
Declaration
enum isRandomAccessRange(R) = is(typeof((inout int = 0)
{
static assert(isBidirectionalRange!R || isForwardRange!R && isInfinite!R);
R r = R.init;
auto e = r[1];
auto f = r.front;
static assert(is(typeof(e) == typeof(f)));
static assert(!isNarrowString!R);
static assert(hasLength!R || isInfinite!R);
static if (is(typeof(r[__dollar])))
{
static assert(is(typeof(f) == typeof(r[__dollar])));
static if (!isInfinite!R)
{
static assert(is(typeof(f) == typeof(r[__dollar - 1])));
}
}
}
));
Example
alias R = int[]; // range is finite and bidirectional or infinite and forward. static assert(isBidirectionalRange!R || isForwardRange!R && isInfinite!R); R r = [0,1]; auto e = r[1]; // can index auto f = r.front; static assert(is(typeof(e) == typeof(f))); // same type for indexed and front static assert(!isNarrowString!R); // narrow strings cannot be indexed as ranges static assert(hasLength!R || isInfinite!R); // must have length or be infinite // $ must work as it does with arrays if opIndex works with $ static if(is(typeof(r[$]))) { static assert(is(typeof(f) == typeof(r[$]))); // $ - 1 doesn't make sense with infinite ranges but needs to work // with finite ones. static if(!isInfinite!R) static assert(is(typeof(f) == typeof(r[$ - 1]))); }
Authors
Andrei Alexandrescu, David Simcha, and Jonathan M Davis. Credit for some of the ideas in building this module goes to Leonardo Maffi.