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 the nth 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.

enum bool isRandomAccessRange(R);

Examples

1 import std.traits : isAggregateType, isAutodecodableString;
2 
3 alias R = int[];
4 
5 // range is finite and bidirectional or infinite and forward.
6 static assert(isBidirectionalRange!R ||
7               isForwardRange!R && isInfinite!R);
8 
9 R r = [0,1];
10 auto e = r[1]; // can index
11 auto f = r.front;
12 static assert(is(typeof(e) == typeof(f))); // same type for indexed and front
13 static assert(!(isAutodecodableString!R && !isAggregateType!R)); // narrow strings cannot be indexed as ranges
14 static assert(hasLength!R || isInfinite!R); // must have length or be infinite
15 
16 // $ must work as it does with arrays if opIndex works with $
17 static if (is(typeof(r[$])))
18 {
19     static assert(is(typeof(f) == typeof(r[$])));
20 
21     // $ - 1 doesn't make sense with infinite ranges but needs to work
22     // with finite ones.
23     static if (!isInfinite!R)
24         static assert(is(typeof(f) == typeof(r[$ - 1])));
25 }

See Also

The header of std.range for tutorials on ranges.

Meta

Suggestion Box / Bug Report