View source code
Display the source code in std/range/primitives.d from which this page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone.

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.

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 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]))); } } } ));


import std.traits : isNarrowString;

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])));


Andrei Alexandrescu, David Simcha, and Jonathan M Davis. Credit for some of the ideas in building this module goes to Leonardo Maffi.


Boost License 1.0.