Enum member std.range.primitives.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.
enum isRandomAccessRange(R)
= is(typeof(lvalueOf!R[1]) == ElementType!R) && !(isAutodecodableString!R && !isAggregateType!R) && isForwardRange!R && (isBidirectionalRange!R || isInfinite!R) && (hasLength!R || isInfinite!R) && (isInfinite!R || !is(typeof(lvalueOf!R[__dollar - 1])) || is(typeof(lvalueOf!R[__dollar - 1]) == ElementType!R));
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
returns a reference to the.opIndex(n) n
th element in the range.
Although char[]
and wchar[]
(as well as their qualified
versions including string
and wstring
) are arrays, isRandomAccessRange
yields false
for them because they use
variable-length encodings (UTF-8 and UTF-16 respectively). These types
are bidirectional ranges only.
See Also
The header of std
for tutorials on ranges.
Example
import std .traits : isAggregateType, isAutodecodableString;
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(!(isAutodecodableString!R && !isAggregateType!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.